Friday, May 07, 2004

Have you ever wanted to sum the values in a DataGrid in ASP.NET on the client side as the user enters them?

Here's how --

1) Create a datagrid with a template column that contains a text box in which the user will type the numbers.
2) In the ItemDataBound event for the datagrid, FindControl the text box, and append its ClientID to a module level variable (comma separated)
3) In the prerender event, generate script to sum the controls and generate a client side array of items that are to be summed.

Snippets

In the ItemDataBound event
Select Case e.Item.ItemType
Case ListItemType.AlternatingItem, ListItemType.Item
Dim ctl As Control
ctl = e.Item.FindControl("txtNumber")
If Not IsNothing(ctl) Then
If _NumberTextBoxes <> "" Then
_NumberTextBoxes&= ", "
End If
_NumberTextBoxes &= "'" & ctl.ClientID & "'"
CType(ctl, TextBox).Attributes.Add("onblur", "UpdateTotals();")
End If
End Select

in the Page.PreRender Event
Dim scr As New System.Text.StringBuilder

scr.Append("<script>")
scr.Append("function UpdateTotals()" & vbCrLf)
scr.Append("{" & vbCrLf)
scr.Append(" var tot;" & vbCrLf)
scr.Append(" if (parseFloat(" & DHTMLElement(txtAmountRequested) & ".value).toString() != 'NaN')" & vbCrLf)
scr.Append(" tot = parseFloat(" & DHTMLElement(txtAmountRequested) & ".value);" & vbCrLf)
scr.Append(" else" & vbCrLf)
scr.Append(" tot = 0;" & vbCrLf)
scr.Append(vbCrLf)
scr.Append(" for (var i=0; i<TextBoxArray.length; i++)" & vbCrLf)
scr.Append(" {" & vbCrLf)
scr.Append(" if (parseFloat(document.getElementById(TextBoxArray[i]).value).toString() != 'NaN')" & vbCrLf)
scr.Append(" tot = tot + parseFloat(document.getElementById(TextBoxArray[i]).value);" & vbCrLf)
scr.Append(" }" & vbCrLf)
scr.Append(vbCrLf)
scr.Append(" " & DHTMLElement(lblTotal) & ".innerHTML = tot;" & vbCrLf)
scr.Append("}" & vbCrLf)
scr.Append("</script>" & vbCrLf)

If Not Me.Page.IsClientScriptBlockRegistered("webRequestScript") Then
Me.Page.RegisterArrayDeclaration("TextBoxArray", _NumberTextBoxes)

Me.Page.RegisterClientScriptBlock("webRequestScript", scr.ToString)

Dim scr2 As New System.Text.StringBuilder
scr2.Append("<script>" & vbCrLf)
scr2.Append("UpdateTotals();" & vbCrLf)
scr2.Append("</script>" & vbCrLf)

Me.Page.RegisterStartupScript("webRequestStart", scr2.ToString)
End If

Thursday, May 06, 2004

Found out an interesting fact on Request.Redirect. It actually throws an error! This is a problem if you have some code like this:

try
... do some processing ...

Request.Redirect("another page.aspx")

catch ex as exception
lblError.text = ex.Message
end try


In this code I don't want to redirect if there is an error in the processing before the Redirect.

To fix, code as follows:
try
... do some processing ...

try
Request.Redirect("another page.aspx")
Catch tae As System.Threading.ThreadAbortException
' Ignore this error that is returned by Redirect
end try

catch ex as exception
lblError.text = ex.Message
end try