Accessing bound controls through javascript
Hi,
firstly this isnt a question, but a general share of knowledge.
we were having some problems on how to access the specific databound controls in a datagrid on the client side,
we did some searching on the net but didnt come up with any posts for it, so here's how we did it
the controls placed in the datagrid templateColumns cannot be accessed directly by their names on the client, when ASP.net
renders the pages in HTML, the control names are replaced in this form:
<datagridname>:_ctl<indexno>:<controlname>
for example, I have a datagrid named dgAmount and i have a bound textbox named txtAmount, now the first instance name of the
text box in the bound grid on the client side would probably render as :
dgAmount:_ctl1:txtAmount
similiar is the case with id , except that the colons are replaced with '_' :
dgAmount__ctl1_txtAmount
now this creates a problem in certain scenrario's for example, if a datagrid has 2 bound text boxes called txtbox1 and
txtbox2, now the value of txtbox2 ios dependant on the value of txtbox1 which the user inputs at runtime, and based on that
value the result is calculated (currency rate conversion for example) and placed in txtbox2
It would be more efficient to deal with this kind of calculation on the client side instead of a whole postback, but the issue on the client side is how to access the target textbox? (txtbox2), for this we came up witha simple javascript method
this is based on our scenario for rate conversion:
function calculateValues(srcControl,dstControlName){
document.getElementById(getTargetControlName(srcCo ntrol,dstControlName)).value = srcControl.value * document.getElementById("txtAmount").value
}
function getTargetControlName(srcControl,dstControlName){
var endIndex = srcControl.name.lastIndexOf(":");
var str = srcControl.name.substring(0,endIndex+1) + dstControlName;
return str; //return the completed target control name
}
to use these functions have them bound to the controls in the Itemdatabound event of the grid :
Private Sub dgCurrency_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgCurrency.ItemDataBound
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
Dim txtbox As TextBox = CType(e.Item.FindControl("txtRate"), TextBox)
txtbox.Attributes.Add("onBlur", "calculateValues(this,""txtValue"")")
End If
End Sub
not that textbox control names here are txtRate and txtvalues, this script can be called on any of the html events instead of onBlur, the source control has to pass itself using the 'this' keyword, the secong argument of the function is the string name of the destination control for which u want to access the value
hope this will help people in a similiar scenario...
|