In some situations we must insert a bunch of data into database table.

Just when we done some entry every entry must first go to gridview after all the entries completion we will push all the data by single click.

For this we need a run-time datatable:

Here is the code:

1) Decalare a Datatable globally.

DataTable dt1;

2) In the event you like place this code:

DataSet ds2 = new DataSet();

if (Session[“dt1”] != null)
{

dt1 = Session[“dt1”] as DataTable;
}
else
{
dt1 = new DataTable();

dt1.Columns.Add(“Name”);
dt1.Columns.Add(“Rollno”);

}
DataRow dr = dt1.NewRow();

dr[“Name”] = TextBox1.Text;
dr[“Rollno”] = TextBox2.Text;

dt1.Rows.Add(dr);

Session[“dt1”] = dt1;
GridView1.DataSource = dt1;
GridView1.DataBind();

3) In the aspx page take a gridview
with boundfields as name and Rollno
4) For Inserting all the gridview values write foreach in button_click event.

foreach (GridViewRow gvr in GridView1.Rows)
{
string name1 = gvr.Cells[0].Text;
string roll = gvr.Cells[1].Text;

string str = “Data Source=RADHE;Initial Catalog=mnc_site;User ID=sa;Password=admin123”;
SqlConnection conn = new SqlConnection(str);

conn.Open();

string insqry = “insert into testing(Name,Rollno) values (@Name,@Rollno)”;

SqlCommand cmd = new SqlCommand(insqry, conn);

cmd.Parameters.Add(“@Name”, SqlDbType.VarChar).Value = name1 ;
cmd.Parameters.Add(“@Rollno”, SqlDbType.VarChar).Value = roll ;

cmd.ExecuteNonQuery();

conn.Close();
}

Any doubts mail me
Advertisements