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
We need a row-created event to bind textbox for each column in a row
- <asp:GridView ID="GridView1" runat="server" OnRowCreated="GridView1_RowCreated"
- OnRowDataBound="GridView1_RowDataBound" ></asp:GridView>
Code behild (.CS) code
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- try
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- for (int colIndex = 0; colIndex < e.Row.Cells.Count; colIndex++)
- {
- int rowIndex = colIndex;
- TextBox txtName = new TextBox();
- txtName.Width = 16;
- txtName.ID = "txtboxname" + colIndex;
- txtName.AutoPostBack = true;
- e.Row.Cells[colIndex].Controls.Add(txtName);
- TextBox txtName1 = new TextBox();
- txtName1.Width = 16;
- txtName1.BackColor = System.Drawing.Color.LightBlue;
- txtName1.ID = "txtboxname1" + colIndex;
- txtName1.ReadOnly = true;
- e.Row.Cells[colIndex].Controls.Add(txtName1);
- }
- }
- }
- }
- catch (Exception ex)
- {
- }
- }
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.


Subhransu MaharanaPosted May 2, 2023, 7:14 AM
How to create dynamically add column in header in textbox gridview in asp.net with data source
Jyoti AgarwalPosted Jul 7, 2020, 6:12 AM
Hey i have added a link button and a textbox dynamically on the footer of the gridview, but when i clicked on the link button after the postback, dynamically added controls not showing on the gridview. Is there any solution ????
Firas AswadPosted Jun 27, 2020, 12:20 PM
How can get value from this textbox (txtboxname1) ?
Kaviarasan APosted Aug 30, 2018, 12:03 AM
To save the girdview data .finding the dynamic textbox problem how to solve this
Swetha ReddyPosted Jun 30, 2017, 2:11 AM
Thnq for sharing the info...sure it will be helpful...