Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Monday, December 14, 2009

Attach JavaScript Events to Grid View Bound Field

I have an <asp:gridview>, can I attach a JavaScript function to the OnKeyPress event of the text boxes (visible while you in Edit mode)?

To achieve that, most of the forums and blog suggested a Template Field instead of a Bound Field where you need to do something custom like that.. (It’s a good solution, for me I implemented grid view with all columns as Bound Field, to modify it’s took more time)

Then I tried with many ways and after that I got solution for attach JavaScript with Bound Field.

Solution
Add “OnRowEditing” event in Grid view
When RowEditing Event
Example using c#
protected void grdView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView oGridView = (GridView)sender;
oGridView.EditIndex = e.NewEditIndex;
TextBox textbox = new TextBox();
textbox = (TextBox)oGridView.Rows[e.NewEditIndex].Cells[4].Controls[0];
textbox.Attributes.Add("onKeyPress", "return numericCheck(event);");
BindData();
}


1. Create an TextBox Object : TextBox textbox = new TextBox();
2. For this example I am going to attach the javascript with 4th column of the current row.oGridView.Rows[e.NewEditIndex].Cells[4].Controls[0]
3. Then type cast the Control as TextBox (TextBox)oGridView.Rows[e.NewEditIndex].Cells[4].Controls[0];
4. Then attach the onKeyPress event - textbox.Attributes.Add("onKeyPress", "return numericCheck(event);");

JavaScript
function numericCheck()
{
if(!(event.keyCode==45event.keyCode==46event.keyCode==48event.keyCode==49event.keyCode==50event.keyCode==51event.keyCode==52event.keyCode==53event.keyCode==54event.keyCode==55event.keyCode==56event.keyCode==57 event.keyCode == 8 event.keyCode == 190 event.keyCode == 37 event.keyCode == 39 event.keyCode == 16))
{
alert("Please Enter Nemeric Values");
event.returnValue=false;
}
}