Dynamically Creating Textbox In Gridview ASP.NET C#

This blog will explain how to create ta ext box dynamically in gridview asp.net and C#. 
 
We are creating the text box with respect to the column index and we can create mutiple textboxes for a gridview column.
 
ASPX Code (Design View)

We need a row-created 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.                    for (int colIndex = 0; colIndex < e.Row.Cells.Count; colIndex++)  
  8.                    {  
  9.                            int rowIndex = colIndex;
  10.                            TextBox txtName = new TextBox();  
  11.                            txtName.Width = 16;  
  12.                            txtName.ID = "txtboxname" + colIndex;   
  13.                            txtName.AutoPostBack = true;  
  14.                            e.Row.Cells[colIndex].Controls.Add(txtName);  
  15.                            TextBox txtName1 = new TextBox();  
  16.                            txtName1.Width = 16;  
  17.                            txtName1.BackColor = System.Drawing.Color.LightBlue;  
  18.                            txtName1.ID = "txtboxname1" + colIndex;  
  19.                            txtName1.ReadOnly = true;  
  20.                            e.Row.Cells[colIndex].Controls.Add(txtName1);
  21.                        }  
  22.                    }  
  23.                }  
  24.   
  25.            }  
  26.            catch (Exception ex)  
  27.            {  
  28.            }  
  29.   
  30.        }     
Description
    • e.Row.Cells.Count -- This will gives you number of columns in the grid view
    • txtName.ID = "txtboxname" + colIndex; -- Creating new textbox, creating ID for and binding the ID to the textbox
    • txtName.AutoPostBack = true; -- Enabling postback funtion for the particular textbox ID to enable events
    • e.Row.Cells[colIndex].Controls.Add(txtName); - Adding textbox item to the grivew(Colindex- column number)
We can add CSS code for the textbox element.
 
We can also add mutiple texboxes and multiple items like label, button etc.
 
Example Image of gridview.
 
Dynamic Column name and textboxes. 
 
Ebook Download
View all
Learn
View all