Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have bind the data from database and show on girdview using this code.
Now I want to add a button on gridview for adding new row on gridview.
Please help me to add new row on gridview.
C#
if (!Page.IsPostBack)
{
    binddata();
}

}
private void binddata()
{
    string connstring = @"Data Source=LENOVO-41B3F2CE\SQLEXPRESS;Initial Catalog=IMS;Integrated Security=True;Pooling=False";
    string query = "SELECT * FROM ['ISB VAS Nodes$']";
    SqlDataAdapter da = new SqlDataAdapter(query, connstring);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
}
Posted
v2

hi,

You can do this in two ways:

1. Either you insert the data in database then bind the new data to Gridview

2. Or else take Gridview data in a datatable and insert data into datatable and then bind new
data from the datatable to Gridview.
 
Share this answer
 
Hi,

copy the datatable to the session, and on click of the button add a row to datatable and bind the gridview with the new datatabl;e and copy the datatable back to session.
C#
private void binddata()
{
    string connstring = @"Data Source=LENOVO-41B3F2CE\SQLEXPRESS;Initial Catalog=IMS;Integrated Security=True;Pooling=False";
    string query = "SELECT * FROM ['ISB VAS Nodes$']";
    SqlDataAdapter da = new SqlDataAdapter(query, connstring);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView1.DataSource = dt;
    Session["data"] = dt; //copy the datatable to session.
    GridView1.DataBind();
}

Button click event :
C#
DataTable dt = ((DataTable)Sessio["data"]);
if(dt != null)
{
    dt.Rows.Add("c1","c2","c3"); // add your the column values
    dt.AcceptChanges();
    GridView1.DataSource = dt;
    Session["data"] = dt; //copy the datatable back to session.
    GridView1.DataBind();
}


further refer below articles.
Insert a new row to gridview[^]
Dynamically adding and deleting rows from ASP.NET GridView[^]

hope it helps.
 
Share this answer
 
Hi..

Write code in your addnewrow button onclick,
just add blow code.


GridView1.ShowFooter=True;
 
Share this answer
 
private void BindGrid(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("TextBox1Column", typeof(String)));

if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();

}
}
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dt.Rows.Add(dr);

}
else
{
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dt.Rows.Add(dr);

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900