virupakshi jekin

virupakshi jekin

  • 1.7k
  • 142
  • 669

Dynamically Creating Data-table and Binding To Grid-view

Aug 30 2018 4:39 AM
Dynamically Creating DataTable and Binding To GridView i want store all gridview data in database at time.
 
Source aspx page
  1. <form id="form1" runat="server">  
  2. <div>  
  3. <asp:TextBox ID="txt_id" runat="server" placeholder="ID"></asp:TextBox><br />  
  4. <asp:TextBox ID="txt_name" runat="server" placeholder="Name"></asp:TextBox><br />  
  5. <asp:Button ID="Button1" runat="server" Text="Button" onclick="btn_1_Click"/>  
  6. <asp:GridView ID="GridView1" runat="server">  
  7. </asp:GridView>  
  8. <asp:Button ID="Button2" runat="server" Text="Button" OnClick="btn_2_Click"/>  
  9. </div>  
  10. </form>  
CS file
  1. protected void btn_1_Click(object sender, EventArgs e)  
  2. {  
  3. GridView1.Visible = true;  
  4. createnewrow();  
  5. }  
  6. public void createnewrow()  
  7. {  
  8. DataTable mytable = new DataTable();  
  9. if (ViewState["Row"] != null)  
  10. {  
  11. mytable = (DataTable)ViewState["Row"];  
  12. DataRow dr = null;  
  13. if (mytable.Rows.Count > 0)  
  14. {  
  15. dr = mytable.NewRow();  
  16. dr["Id"] = txt_id.Text;  
  17. dr["Name"] = txt_name.Text;  
  18. mytable.Rows.Add(dr);  
  19. ViewState["Row"] = mytable;  
  20. GridView1.DataSource = ViewState["Row"];  
  21. GridView1.DataBind();  
  22. }  
  23. }  
  24. else  
  25. {  
  26. mytable.Columns.Add("Id"typeof(int));  
  27. mytable.Columns.Add(new DataColumn("Name"typeof(string)));  
  28. DataRow dr1 = mytable.NewRow();  
  29. dr1 = mytable.NewRow();  
  30. dr1["Id"] = txt_id.Text;  
  31. dr1["Name"] = txt_name.Text;  
  32. mytable.Rows.Add(dr1);  
  33. ViewState["Row"] = mytable;  
  34. GridView1.DataSource = ViewState["Row"];  
  35. GridView1.DataBind();  
  36. }  
  37. }  
  38. // this is my save button  
  39. protected void btn_2_Click(object sender, EventArgs e)  
  40. {  
  41. con.Open();  
  42. SqlCommand com = new SqlCommand("tbl_adda", con);  
  43. com.CommandType = CommandType.StoredProcedure;  
  44. com.Parameters.AddWithValue("@Id", Convert.ToInt32(txt_id.Text));  
  45. com.Parameters.AddWithValue("@Name", txt_name.Text.ToString());  
  46. com.ExecuteNonQuery();  
  47. con.Close();  
  48. }  
please help me

Answers (3)