why you are filling data in gridview data bound.i did n't understand.Do one thing create one method
like
public void bindgrid()
{
}
and call it in page load event
if(!ispostback)
{
bindgrid();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtToGrid = new DataTable();
dtToGrid.Columns.Add("UserName", typeof(string));
dtToGrid.Columns.Add("Password", typeof(string));
Session["dtToGrid"] = dtToGrid;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dtToGrid = (DataTable)Session["dtToGrid"];
DataRow drToGrid = dtToGrid.NewRow();
drToGrid["UserName"] = TextBox1.Text.Trim();
drToGrid["Password"] = TextBox2.Text.Trim();
dtToGrid.Rows.Add(drToGrid);
GridView1.DataSource = dtToGrid;
GridView1.DataBind();
TextBox1.Text = "";
}
protected void Button2_Click(object sender, EventArgs e)
{
cn.Open();
DataTable dt = (DataTable)Session["dtToGrid"];
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.DestinationTableName = "userdetails";
copy.WriteToServer(dt);
}
Page.RegisterStartupScript("<script>", "<script>alert('Successfully Saved')</script>");
}