Create dynamic GridView rows and columns with TextBox in each cell based on row and column value from TextBox using C# in ASP.Net

Last Reply on Jul 11, 2017 09:19 AM By AnandM

Posted on Jul 11, 2017 02:14 AM

Hai all,
i need small request. In my query i want to create gridview dynamically.
example if i enter rows as 2 and columns as 3 then it creates 2 rows and 3 columns with editable textboxes in gridview.

if anybody understand please help me

Thanks in advance

Posted on Jul 11, 2017 09:19 AM

Hi nagaraju60,

I have created a sample which full fill your requirement you need to modify the code according to your need.

HTML

<div>
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    Columns
                </td>
                <td>
                    <asp:TextBox ID="txtColumns" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    Rows
                </td>
                <td>
                    <asp:TextBox ID="txtRows" runat="server" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSubmit" OnClick="GenerateGridView" Text="Submit" runat="server" />
                </td>
            </tr>
        </table>
        <br />
        <asp:GridView ID="gvData" runat="server" />
</div>

C#

protected void GenerateGridView(object sender, EventArgs e)
{
    gvData.Columns.Clear();
    DataTable dt = new DataTable();
    int cols = Convert.ToInt32(txtColumns.Text.Trim());
    int rows = Convert.ToInt32(txtRows.Text.Trim());
    for (int i = 0; i < cols; i++)
    {
        TemplateField field = new TemplateField();
        field.HeaderText = "Column" + i.ToString();
        field.ItemTemplate = new GridViewTemplate("Column" + i.ToString(), i.ToString());
        gvData.Columns.Add(field);
    }

    for (int i = 0; i < rows; i++)
    {
        dt.Rows.Add();
    }
    gvData.DataSource = dt;
    gvData.DataBind();
}

public class GridViewTemplate : ITemplate
{
    private string columnNameBinding;

    public GridViewTemplate(string colname, string colNameBinding)
    {
        columnNameBinding = colNameBinding;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        TextBox tb = new TextBox();
        tb.ID = "txtDynamic" + columnNameBinding;
        container.Controls.Add(tb);
    }
}

ScreenShot