As you have mentioned i have removed the Edit Button and Added back a Insert Button. Here i tried to add a OnClick Event for the Button but its says OnClick is Inaccessible due to its Protection level so i have added a OnClientClick event.
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">
<Columns>
<asp:ButtonField Text="Edit" CommandName="Edit" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" Text="AddRow" OnClick="AddRows" runat="server" />
</div>
<script type="text/javascript">
function Insert() {
debugger;
}</script>
</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;
this.GridView1.Rows[rowsCount - 1].Cells[0].Controls.RemoveAt(0);
Button btn = new Button();
btn.Attributes.Add("runat", "server");
btn.ID = "btnInsert";
btn.Text = "Insert";
btn.OnClientClick = "Insert();";
this.GridView1.Rows[rowsCount - 1].Cells[0].Controls.Add(btn);
for (int i = 1; i < 3; i++)
{
Label label = new Label();
label.ID = "lblNewLabel" + i.ToString();
label.Attributes.Add("runat", "server");
label.Text = "add your Randome Value";
this.GridView1.Rows[rowsCount - 1].Cells[i].Controls.Add(label);
}
for (int j = 3; 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["constr2"].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();
}
}
}
}
it will be Better for you to have the Button Out Side of the GridView because it will be difficult to find and add records in JavaScript for the Sql tables .. Its Your Choice.