Fahhad
Fahhad

Reputation: 85

How to extract data from a TextBox to a GridView (multiple rows to be displayed in the GridView)?

I have used the following code to display data from a TextBox to a GridView without saving the data to the database(Two TextBoxes and a Button). When I enter the Name and City in the TextBoxes, and click on the Button, those values will be displayed in the Gridview. It is working as expected without any errors. But I want to tweak the code a bit so that the GridView should be able to add new data from the Textbox by retaining the old data as it is in the Gridview (multiple rows should be displayed in the Gridview instead of single rows).

It is a web-based ASP.NET application using C# coding (Visual Studio 2010).

Can you make the necessary changes to the code given below so as to implement the above functionality?

public partial class _Default : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();

protected void Page_Load(object sender, EventArgs e)
    {

    }

protected void btnTextDisplay_Click(object sender, EventArgs e)
    {
            DataColumn dc1 = new DataColumn("Name");
            DataColumn dc2 = new DataColumn("City");
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);

            DataRow dr = dt.NewRow();
            dr[0] = txtName.Text;
            dr[1] = txtCity.Text;
            dt.Rows.Add(dr);
            gvDisplay.DataSource = dt;
            gvDisplay.DataBind();
    }
}

Upvotes: 0

Views: 2897

Answers (1)

gzaxx
gzaxx

Reputation: 17600

You have to persists your data between postbacks, you have many options here: by Session, ViewState, Cache and some other.

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostback)
    {
         dt = Session["data_table"] as DataTable;
    }
}

protected void btnTextDisplay_Click(object sender, EventArgs e)
{
     if (dt == null)
     {
          dt = new DataTable();
          DataColumn dc1 = new DataColumn("Name");
          DataColumn dc2 = new DataColumn("City");
          dt.Columns.Add(dc1);
          dt.Columns.Add(dc2);   
     }

     DataRow dr = dt.NewRow();
     dr[0] = txtName.Text;
     dr[1] = txtCity.Text;
     dt.Rows.Add(dr);
     gvDisplay.DataSource = dt;
     gvDisplay.DataBind();

     Session["data_table"] = dt;
}

Upvotes: 2

Related Questions