Dynamically Add JavaScript To The Grid View TextBox

Create the texbox and add JavaScript to the dynamically created textbox in Grid View.
 
ASPX Code (Design View)
 
We need a RowCreated event to bind textbox for each column in a row.
  1. <asp:GridView ID="GridView1" runat="server" OnRowCreated="GridView1_RowCreated"
  2. OnRowDataBound="GridView1_RowDataBound" ></asp:GridView>
Code behild (.CS) code
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.        {  
  3.            try  
  4.            {  
  5.                if (e.Row.RowType == DataControlRowType.DataRow)  
  6.                {                      
  7.   
  8.                    for (int colIndex = 5; colIndex < e.Row.Cells.Count; colIndex++)  
  9.                    { 
  10.                            int rowIndex = colIndex;
  11.                            TextBox txtName = new TextBox();  
  12.                            txtName.Width = 16;  
  13.                            txtName.ID = "txtGiveQty" + colIndex;  
  14.                            string txtID = "txtGiveQty" + colIndex;  
  15.                            e.Row.Cells[colIndex].Controls.Add(txtName);                                                   
  16.                            txtName.Attributes.Add("onChange""return SetBalanceAmountGID(this,'"+locationame +"','txtGiveQty')");  
  17.                            txtName.AutoPostBack = true;  
  18.                            e.Row.Cells[colIndex].Controls.Add(txtName);  
  19.                           
  20.                        }  
  21.                    }  
  22.                }  
  23.   
  24.            }  
  25.            catch (Exception ex)  
  26.            {  
  27.            }  
  28.   
  29.        }      
Description
  1. e.Row.Cells.Count -- This will gives you number of columns in the grid view
  2. txtName.ID = "txtboxname" + colIndex; -- Creating new textbox, creating ID for and binding the ID to the textbox
  3. txtName.AutoPostBack = true; -- Enabling postback funtion for the particular textbox ID to enable events
  4. e.Row.Cells[colIndex].Controls.Add(txtName); - Adding textbox item to the grivew(Colindex- column number)
  5. textbox.Attributes.Add("onChange", "return function(paramaters)");
     
    Eg : textbox.Attributes.Add("onChange", "return SetBalanceAmountGID(this,'1')");
Java script
  1. function SetBalanceAmountGID(obj, value) {    
  2.               
  3.          alert(value)  
  4. // Write the script here   
  5. }  
We can also add multiple textboxes and multiple items like labels, button, etc.