views:

357

answers:

1

Hi, I've a grid view and I want to bind some data to this Gridview at runtime.

In my button click event I wrote like this

protected void Button1_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    DataRow dr;
    DataColumn dc = new DataColumn();
        dc.Caption = "Name";
        dc.DataType = Type.GetType("System.String");
        dc.ColumnName = "Name";
        dt.Columns.Add(dc);


    dr = dt.NewRow();
    dr["Name"] = TextBox1.Text;
    dt.Rows.Add(dr);
    ds.Tables.Add(dt);
    GridView1.DataSource = ds;
    GridView1.DataBind();

}

It is working fine and displays data. But now I want to add multiple rows to gridview. When I try to bind it only one row adding to grid view every time. (i.e recent value entered in text box). I want to append rows to gridview.

How can I do this?

A: 

Store ds to a viewstate.

Then when you r adding a new row. Retrieve the dataset from viewstate and add a new row containing recent value entered in text box.

as :

if(ViewState["ds"]!=null)
{
DataSet ds=(DataSet) ViewState["ds"];
 dr = ds.Tables[0].NewRow();
 dr["Name"] = TextBox1.Text;
 ds.Tables[0].Rows.Add(dr);
 GridView1.DataSource = ds;
 GridView1.DataBind();
}
Himadri