klgrube
asked on
How to display an Alert Message from asp.net 2.0 GridView when delete fails.
Hi!
I'm trying to get an alert box to display when a user hits the 'delete' link button in a Gridview and the item they've selected shouldn't be deleted. I'm using Visual Studio 2005 and asp.net 2.0. Really, this should just be a little alert box they 'okay' out of, nothing more.
The Gridview on this web form simply displays Customers and Customer Names, and then Edit and Delete controls. The Customer Number is the key value, so it's not editable, but the name is. Still, users need to be able to delete unused or invalid customer records from this list.
I already have a box popping up asking if the user really wants to delete the record. I'm using a template field in the gridview for that
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="false" CommandName="Delete"
OnClientClick="return confirm ('Okay to delete this customer?');" Text="Delete" style="vertical-align: middle; text-align: center" Font-Bold="False" ForeColor="Black" Height="3px" Width="49px"></asp:LinkBut ton>
</ItemTemplate>
This works well. But it occurred to me that what I really want to do is check to see if the customer already has orders before it can be delete from this list. So, I created a 'RowDeleting' subroutine. It does work in the sense that it prevents users from deleteing customers that have orders. It's just that my alert box doesn't display telling them what happened and it causes the page to redisplay! I really have no clue how to use the 'ClientScript.RegisterStar tupScript stuff you see in the last few lines of the code below. I have no clue what the 'type' or 'key' are supposed to be that are the parameters for the command. In fact, I'm not even sure if 'registerstartupscript' is the correct thing to use. Is this a 'startup" script? Maybe I should turn 'Causes Validation' back on and use some kind of custom validation routine instead, though I'm clueless as to how to do that too in a template link button. Or, I could create a 'delete' trigger on the customer table that would fail the delete, but I'm not sure how to display a 'could not delete' message in that circumstance either.
Again, all I'm trying to do is alert users they aren't allowed to delete customers when they already have orders. How dumb is it that after all these years, there still isn't an easy way to send an alert message like that to the screen?
-------------------------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------
Protected Sub gv_Customers_RowDeleting(B yVal sender As Object, ByVal e As System.Web.UI.WebControls. GridViewDe leteEventA rgs) Handles gv_GrandeCustomers.RowDele ting
Dim cn As New SqlConnection(System.Confi guration.C onfigurati onManager. Connection Strings("M yConnectio nString"). Connection String)
Dim cmd As New SqlCommand
Dim NumberofOrders As New Int32
NumberofOrders = 0
Dim CustomerName As String = e.Keys(0).ToString
With cmd
.Connection = cn
.CommandText = "select count(*) from Order_Header where CUSTOMER_NAME = @CustomerName"
.CommandType = Data.CommandType.Text
.Parameters.Add("@Customer Name", System.Data.SqlDbType.VarC har)
.Parameters("@CustomerName ").Value = CustomerName
End With
Try
cn.Open()
Catch ex As Exception
End Try
Dim CmdReader As SqlDataReader = cmd.ExecuteReader()
Try
CmdReader.Read()
NumberofOrders = CmdReader(0)
End Try
If NumberofOrders > 0 Then
e.Cancel = True
Dim strMessage As String
strMessage = "This customer has orders and cannot be deleted."
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(""" & strMessage & """);"
strScript += "</script>"
If (Not ClientScript.IsStartupScri ptRegister ed("client Script")) Then
ClientScript.RegisterStart upScript(M e.GetType( ), "clientScript", "clientScript")
End If
End If
End Sub
__________________________ __________ __________ __________ __________ __________ __________ __________ ___
Thanks!
Karen
I'm trying to get an alert box to display when a user hits the 'delete' link button in a Gridview and the item they've selected shouldn't be deleted. I'm using Visual Studio 2005 and asp.net 2.0. Really, this should just be a little alert box they 'okay' out of, nothing more.
The Gridview on this web form simply displays Customers and Customer Names, and then Edit and Delete controls. The Customer Number is the key value, so it's not editable, but the name is. Still, users need to be able to delete unused or invalid customer records from this list.
I already have a box popping up asking if the user really wants to delete the record. I'm using a template field in the gridview for that
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="false" CommandName="Delete"
OnClientClick="return confirm ('Okay to delete this customer?');" Text="Delete" style="vertical-align: middle; text-align: center" Font-Bold="False" ForeColor="Black" Height="3px" Width="49px"></asp:LinkBut
</ItemTemplate>
This works well. But it occurred to me that what I really want to do is check to see if the customer already has orders before it can be delete from this list. So, I created a 'RowDeleting' subroutine. It does work in the sense that it prevents users from deleteing customers that have orders. It's just that my alert box doesn't display telling them what happened and it causes the page to redisplay! I really have no clue how to use the 'ClientScript.RegisterStar
Again, all I'm trying to do is alert users they aren't allowed to delete customers when they already have orders. How dumb is it that after all these years, there still isn't an easy way to send an alert message like that to the screen?
--------------------------
Protected Sub gv_Customers_RowDeleting(B
Dim cn As New SqlConnection(System.Confi
Dim cmd As New SqlCommand
Dim NumberofOrders As New Int32
NumberofOrders = 0
Dim CustomerName As String = e.Keys(0).ToString
With cmd
.Connection = cn
.CommandText = "select count(*) from Order_Header where CUSTOMER_NAME = @CustomerName"
.CommandType = Data.CommandType.Text
.Parameters.Add("@Customer
.Parameters("@CustomerName
End With
Try
cn.Open()
Catch ex As Exception
End Try
Dim CmdReader As SqlDataReader = cmd.ExecuteReader()
Try
CmdReader.Read()
NumberofOrders = CmdReader(0)
End Try
If NumberofOrders > 0 Then
e.Cancel = True
Dim strMessage As String
strMessage = "This customer has orders and cannot be deleted."
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(""" & strMessage & """);"
strScript += "</script>"
If (Not ClientScript.IsStartupScri
ClientScript.RegisterStart
End If
End If
End Sub
__________________________
Thanks!
Karen
ASP.Net will not let you activate a meesage box through someone's browser. What you have to do is set up a piece of javascipt with and Alert window. This should only be writting on the page if there is a failure. Then you should set an onload event in the body tag of the page that will call the javascript function. It may sound complicated, but it is really quite easy.
ASKER
Sorry, but I thought that was what I was doing at the end of this code you see above. The problem seems to be that I can't get the parameters right for the ClientScript.RegisterStart upScript command. I don't have the syntax correct. I don't know what the possible 'types' or 'keys' called for by that command are. I should be able to inject client side script here - in the rowdeleting sub - but I'm not sure.
What am I doing wrong? Any guidance (sample code) would be appreciated. And please don't point me to the samples online. I've googled this several different ways and I keep coming up with code that works with ASP.Net 1.1 but that don't have this new method for calling client script. And I can't find any examples of it anywhere - not that are at all like what I need.
Thanks!
Karen
What am I doing wrong? Any guidance (sample code) would be appreciated. And please don't point me to the samples online. I've googled this several different ways and I keep coming up with code that works with ASP.Net 1.1 but that don't have this new method for calling client script. And I can't find any examples of it anywhere - not that are at all like what I need.
Thanks!
Karen
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks so much!
This works well, with one tiny exception. When the error message pops up, instead of popping up on the Customer List Entry Screen, a blank screen pops up with the message in the center. When you click 'OK' it goes back to the Customer Entry Screen. It's as though it's taking "Me" to be a page created by the new class or something. I'm not sure. Any suggestions?
Thanks again! This really is terrific!
Karen
This works well, with one tiny exception. When the error message pops up, instead of popping up on the Customer List Entry Screen, a blank screen pops up with the message in the center. When you click 'OK' it goes back to the Customer Entry Screen. It's as though it's taking "Me" to be a page created by the new class or something. I'm not sure. Any suggestions?
Thanks again! This really is terrific!
Karen
You welcome Karen,
I tried it and I didnt see this behaviour at all.
Can you show me some of your code where the Message is involved? Maybe I can find out what's casuing this.
Sammy
I tried it and I didnt see this behaviour at all.
Can you show me some of your code where the Message is involved? Maybe I can find out what's casuing this.
Sammy
ASKER
Hi!
Here's the code for the class. . . VS 2005 added it to a folder called App_Code and added the import for Microsoft.Visual Basic
__________________________ __________ __________ __________
Imports Microsoft.VisualBasic
Public Class ClientAlert
Public Sub CreateClientAlert(ByVal Message As String, ByVal objPage As Page)
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">" )
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & Message & "');")
.Append(vbCrLf)
.Append("</script>")
End With
If Not objPage.ClientScript.IsCli entScriptB lockRegist ered("Aler tBox") Then
objPage.ClientScript.Regis terClientS criptBlock (Me.GetTyp e, "AlertBox", StrScript.ToString)
End If
End Sub
End Class
__________________________ __________ __________ __________ __________ __________ __________ _
Here's the relevant code for the client list form . . .
__________________________ __________ __________ __________ __________ __________ __________ _
Imports System
Imports System.Security.Principal
Imports System.Data
Imports System.Data.SqlClient
Partial Class Grande_Customer_Update
Inherits System.Web.UI.Page
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim wp As WindowsPrincipal = New WindowsPrincipal(WindowsId entity.Get Current())
lblUserWelcome.Text = "Welcome " & wp.Identity.Name
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub gv_GrandeCustomers_RowDele ting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls. GridViewDe leteEventA rgs) Handles gv_GrandeCustomers.RowDele ting
Dim cn As New SqlConnection(System.Confi guration.C onfigurati onManager. Connection Strings("M yConnectio nString"). Connection String)
Dim cmd As New SqlCommand
Dim NumberofOrders As New Int32
NumberofOrders = 0
Dim CustomerName As String = e.Keys(0).ToString
With cmd
.Connection = cn
.CommandText = "select count(*) from Order_Header where CUSTOMER_NUMBER = @CustomerName"
.CommandType = Data.CommandType.Text
.Parameters.Add("@Customer Name", System.Data.SqlDbType.VarC har)
.Parameters("@CustomerName ").Value = CustomerName
End With
Try
cn.Open()
Catch ex As Exception
End Try
Dim CmdReader As SqlDataReader = cmd.ExecuteReader()
Try
CmdReader.Read()
NumberofOrders = CmdReader(0)
Catch ex As Exception
' testlogin = "Reader"
End Try
If NumberofOrders > 0 Then
e.Cancel = True
Dim strMessage As String
strMessage = "Customer '" & CustomerName & "' has orders and cannot be deleted."
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">" )
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & strMessage & "');")
.Append(vbCrLf)
.Append("</script>")
End With
Dim objClientAlert As New ClientAlert
objClientAlert.CreateClien tAlert(str Message, Me.Page)
End If
End Sub
End Class
__________________________ __________ __________ __________ __________ __________ __________ ___
Well, that's it. Pretty simple. I wonder if there's something in the GlobalASAX file or WebConfig - or even something set up oddly in IIS. Let me know if you have any ideas . . .
Thanks again!
Karen
Here's the code for the class. . . VS 2005 added it to a folder called App_Code and added the import for Microsoft.Visual Basic
__________________________
Imports Microsoft.VisualBasic
Public Class ClientAlert
Public Sub CreateClientAlert(ByVal Message As String, ByVal objPage As Page)
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">"
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & Message & "');")
.Append(vbCrLf)
.Append("</script>")
End With
If Not objPage.ClientScript.IsCli
objPage.ClientScript.Regis
End If
End Sub
End Class
__________________________
Here's the relevant code for the client list form . . .
__________________________
Imports System
Imports System.Security.Principal
Imports System.Data
Imports System.Data.SqlClient
Partial Class Grande_Customer_Update
Inherits System.Web.UI.Page
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim wp As WindowsPrincipal = New WindowsPrincipal(WindowsId
lblUserWelcome.Text = "Welcome " & wp.Identity.Name
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub gv_GrandeCustomers_RowDele
Dim cn As New SqlConnection(System.Confi
Dim cmd As New SqlCommand
Dim NumberofOrders As New Int32
NumberofOrders = 0
Dim CustomerName As String = e.Keys(0).ToString
With cmd
.Connection = cn
.CommandText = "select count(*) from Order_Header where CUSTOMER_NUMBER = @CustomerName"
.CommandType = Data.CommandType.Text
.Parameters.Add("@Customer
.Parameters("@CustomerName
End With
Try
cn.Open()
Catch ex As Exception
End Try
Dim CmdReader As SqlDataReader = cmd.ExecuteReader()
Try
CmdReader.Read()
NumberofOrders = CmdReader(0)
Catch ex As Exception
' testlogin = "Reader"
End Try
If NumberofOrders > 0 Then
e.Cancel = True
Dim strMessage As String
strMessage = "Customer '" & CustomerName & "' has orders and cannot be deleted."
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">"
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & strMessage & "');")
.Append(vbCrLf)
.Append("</script>")
End With
Dim objClientAlert As New ClientAlert
objClientAlert.CreateClien
End If
End Sub
End Class
__________________________
Well, that's it. Pretty simple. I wonder if there's something in the GlobalASAX file or WebConfig - or even something set up oddly in IIS. Let me know if you have any ideas . . .
Thanks again!
Karen
Karen, You are creating 2 Javascripts here :-)
Your code behinde for Grande_Customer_Update Class should look like this
__________________________ __________ __________ __________ __________ __________ __________ _
Imports System
Imports System.Security.Principal
Imports System.Data
Imports System.Data.SqlClient
Partial Class Grande_Customer_Update
Inherits System.Web.UI.Page
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim wp As WindowsPrincipal = New WindowsPrincipal(WindowsId entity.Get Current())
lblUserWelcome.Text = "Welcome " & wp.Identity.Name
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub gv_GrandeCustomers_RowDele ting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls. GridViewDe leteEventA rgs) Handles gv_GrandeCustomers.RowDele ting
Dim cn As New SqlConnection(System.Confi guration.C onfigurati onManager. Connection Strings("M yConnectio nString"). Connection String)
Dim cmd As New SqlCommand
Dim NumberofOrders As New Int32
NumberofOrders = 0
Dim CustomerName As String = e.Keys(0).ToString
With cmd
.Connection = cn
.CommandText = "select count(*) from Order_Header where CUSTOMER_NUMBER = @CustomerName"
.CommandType = Data.CommandType.Text
.Parameters.Add("@Customer Name", System.Data.SqlDbType.VarC har)
.Parameters("@CustomerName ").Value = CustomerName
End With
Try
cn.Open()
Catch ex As Exception
End Try
Dim CmdReader As SqlDataReader = cmd.ExecuteReader()
Try
CmdReader.Read()
NumberofOrders = CmdReader(0)
Catch ex As Exception
' testlogin = "Reader"
End Try
If NumberofOrders > 0 Then
e.Cancel = True
Dim strMessage As String
strMessage = "Customer '" & CustomerName & "' has orders and cannot be deleted."
'NOTE your script call is removed from here, Dont add anything since objClientAlert will take care of the script for you
Dim objClientAlert As New ClientAlert
objClientAlert.CreateClien tAlert(str Message, Me)
End If
End Sub
End Class
__________________________ __________ __________ __________ __________ __________ __________ __________ ______
The ClientAlertClass should stay the same
Imports Microsoft.VisualBasic
Public Class ClientAlert
Public Sub CreateClientAlert(ByVal Message As String, ByVal objPage As Page)
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">" )
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & Message & "');")
.Append(vbCrLf)
.Append("</script>")
End With
If Not objPage.ClientScript.IsCli entScriptB lockRegist ered("Aler tBox") Then
objPage.ClientScript.Regis terClientS criptBlock (Me.GetTyp e, "AlertBox", StrScript.ToString)
End If
End Sub
End Class
__________________________ __________ __________ __________ ____
Now the script should run fine without any interruptions or other popups in its way :-)
Your code behinde for Grande_Customer_Update Class should look like this
__________________________
Imports System
Imports System.Security.Principal
Imports System.Data
Imports System.Data.SqlClient
Partial Class Grande_Customer_Update
Inherits System.Web.UI.Page
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim wp As WindowsPrincipal = New WindowsPrincipal(WindowsId
lblUserWelcome.Text = "Welcome " & wp.Identity.Name
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub gv_GrandeCustomers_RowDele
Dim cn As New SqlConnection(System.Confi
Dim cmd As New SqlCommand
Dim NumberofOrders As New Int32
NumberofOrders = 0
Dim CustomerName As String = e.Keys(0).ToString
With cmd
.Connection = cn
.CommandText = "select count(*) from Order_Header where CUSTOMER_NUMBER = @CustomerName"
.CommandType = Data.CommandType.Text
.Parameters.Add("@Customer
.Parameters("@CustomerName
End With
Try
cn.Open()
Catch ex As Exception
End Try
Dim CmdReader As SqlDataReader = cmd.ExecuteReader()
Try
CmdReader.Read()
NumberofOrders = CmdReader(0)
Catch ex As Exception
' testlogin = "Reader"
End Try
If NumberofOrders > 0 Then
e.Cancel = True
Dim strMessage As String
strMessage = "Customer '" & CustomerName & "' has orders and cannot be deleted."
'NOTE your script call is removed from here, Dont add anything since objClientAlert will take care of the script for you
Dim objClientAlert As New ClientAlert
objClientAlert.CreateClien
End If
End Sub
End Class
__________________________
The ClientAlertClass should stay the same
Imports Microsoft.VisualBasic
Public Class ClientAlert
Public Sub CreateClientAlert(ByVal Message As String, ByVal objPage As Page)
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">"
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & Message & "');")
.Append(vbCrLf)
.Append("</script>")
End With
If Not objPage.ClientScript.IsCli
objPage.ClientScript.Regis
End If
End Sub
End Class
__________________________
Now the script should run fine without any interruptions or other popups in its way :-)
if you still have a problem with this email me the source for the project at "sageil at shaw .ca"
Sammy
Sammy
ASKER
I'm sorry!
When I saw that behavior, I tried moving the code into the main page as a test, but that didn't work either. I've reset the code exactly the way you originally described, and I'm still having the same problem, where a separate blank window opens up and the message box displays. The message "Error on page" also displays at the bottom of the page.
I can't actually send you the project, but what I can do is create a new test project that has only the class and a form that sets a message and uses the class. I'll try it anyway. My guess is that I have something weird set, like a popup blocker or some setting in the web config or global asax files
I'll let you know how that goes. In the meantime, if you can think of anything, let me know!
Thanks!
Karen
When I saw that behavior, I tried moving the code into the main page as a test, but that didn't work either. I've reset the code exactly the way you originally described, and I'm still having the same problem, where a separate blank window opens up and the message box displays. The message "Error on page" also displays at the bottom of the page.
I can't actually send you the project, but what I can do is create a new test project that has only the class and a form that sets a message and uses the class. I'll try it anyway. My guess is that I have something weird set, like a popup blocker or some setting in the web config or global asax files
I'll let you know how that goes. In the meantime, if you can think of anything, let me know!
Thanks!
Karen
ASKER
Hi!
Thanks, Sammy! Your help was terrific. I found the solution to the one remaining problem at the end of this article.
Implementing a Dialog Box in ASP.NET Based Web Application By Firoz Ansari
http://www.dotnetjunkies.com/Article/A72FCFD7-3874-408A-8FCE-541BEC74C704.dcik
Basically, all we had to do was use RegisterStartupScript. The article explains why.
Here's the final code for the class:
__________________________ __________ __________ __________ __________ __________ ______
Imports Microsoft.VisualBasic
Public Class ClientAlert
Public Sub CreateClientAlert(ByVal Message As String, ByVal objPage As Page)
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">" )
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & Message & "');")
.Append(vbCrLf)
.Append("</script>")
End With
If Not objPage.ClientScript.IsCli entScriptB lockRegist ered("Aler tBox") Then
objPage.ClientScript.Regis terStartup Script(Me. GetType, "AlertBox", StrScript.ToString)
End If
End Sub
End Class
__________________________ __________ __________ __________ ____
Thanks again!
Karen
Thanks, Sammy! Your help was terrific. I found the solution to the one remaining problem at the end of this article.
Implementing a Dialog Box in ASP.NET Based Web Application By Firoz Ansari
http://www.dotnetjunkies.com/Article/A72FCFD7-3874-408A-8FCE-541BEC74C704.dcik
Basically, all we had to do was use RegisterStartupScript. The article explains why.
Here's the final code for the class:
__________________________
Imports Microsoft.VisualBasic
Public Class ClientAlert
Public Sub CreateClientAlert(ByVal Message As String, ByVal objPage As Page)
Dim StrScript As New StringBuilder("")
With StrScript
.Append("<script type=""text/javascript"">"
.Append(vbCrLf)
.Append(vbCrLf)
.Append("alert('" & Message & "');")
.Append(vbCrLf)
.Append("</script>")
End With
If Not objPage.ClientScript.IsCli
objPage.ClientScript.Regis
End If
End Sub
End Class
__________________________
Thanks again!
Karen
I am glad you got it figured out :-)
for some weird reason I have not been able to get that behavior using Firefox
Thanks for the points
Sammy
for some weird reason I have not been able to get that behavior using Firefox
Thanks for the points
Sammy