Here i am binding the Gridview based on the DropDownList. I set the AutoGenerateColumn to true for the Gridview and at the last row of the Gridview i have added a empty row for the TextBox to be added.
HTML:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlTables" runat="server" AutoPostBack="true" OnSelectedIndexChanged="TablesSelectedIndexChanged">
<asp:ListItem Text="Customers" Value="0" />
<asp:ListItem Text="Customers" Value="1" />
<asp:ListItem Text="Employees" Value="2" />
<asp:ListItem Text="Suppliers" Value="3" />
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
<asp:Button Text="AddRow" OnClick="AddRows" runat="server" />
</div>
</form>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetTable("Customers");
}
}
protected void TablesSelectedIndexChanged(object sender, EventArgs e)
{
GetTable(ddlTables.SelectedItem.Text);
}
protected void AddRows(object sender, EventArgs e)
{
int cellCount = this.GridView1.Rows[0].Cells.Count;
int rowsCount = this.GridView1.Rows.Count;
for (int j = 0; j < cellCount; j++)
{
//here i am adding a control.
TextBox textBox = new TextBox();
textBox.ID = "txtDynamicText" + j.ToString();
textBox.Attributes.Add("runat", "server");
textBox.CssClass = "Color";
this.GridView1.Rows[rowsCount - 1].Cells[j].Controls.Add(textBox);
}
}
private void GetTable(string tableName)
{
string strcon = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string sqlStatment = String.Format("SELECT * FROM {0}", tableName);
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
//adding a line where textbox have to be added
DataRow row = dt.NewRow();
dt.Rows.InsertAt(row, dt.Rows.Count);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
con.Close();
}
}
}
}
i have used the Northwind Database. You can dowload it from here.
http://northwinddatabase.codeplex.com/releases/view/71634