Assuming that your
TextBox
and
DropDown
controls are outside GridView. Here's an example how to add rows in
GridView
based from server control values:
ASPX
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:TextBox ID="TextBox2" runat="server"/>
<asp:TextBox ID="TextBox3" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
CODE BEHIND:
private void BindGrid(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("TextBox1Column", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("TextBox2Column", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("TextBox3Column", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
}
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
ViewState["CurrentData"] = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGrid(count);
}
else
{
BindGrid(1);
}
TextBox1.Text = string.Empty;
TextBox1.Focus();
}
In case your server controls are within GridView and you want to generate rows dynamically, then here's a complete step-by-step example that I wrote a few years ago:
https://www.codeproject.com/Articles/1109899/Dynamically-Adding-and-Deleting-Rows-in-GridView-a