This article describes on how to add multiple columns and rows in GridView without using a database. Basically the GridView will be populated with data based on the values entered in each TextBoxes on Button Click and retain the GridView data on post back.
STEP 1:
Add Three TextBox, One Button and One GridView control the web form. The ASPX mark-up should look like these below
<asp:TextBox ID="TextBox1" runat="server"/> <asp:TextBox ID="TextBox2" runat="server"/> <asp:TextBox ID="TextBox3" runat="server"/> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> <asp:GridView ID="GridView1" runat="server" > </asp:GridView> |
STEP 2:
Create the method that will BIND the GridView based on the TextBox values and retain its values on post backs.
private void BindGrid(int rowcount) { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new System.Data.DataColumn("TextBox1Column", typeof(String))); dt.Columns.Add(new System.Data.DataColumn("TextBox2Column", typeof(String))); dt.Columns.Add(new System.Data.DataColumn("TextBox3Column", 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; dr[1] = TextBox2.Text; dr[2] = TextBox3.Text; dt.Rows.Add(dr); } else { dr = dt.NewRow(); dr[0] = TextBox1.Text; dr[1] = TextBox2.Text; dr[2] = TextBox3.Text; dt.Rows.Add(dr); } // If ViewState has a data then use the value as the DataSource if (ViewState["CurrentData"] != null) { GridView1.DataSource = (DataTable)ViewState["CurrentData"]; GridView1.DataBind(); } else { // Bind GridView with the initial data assocaited in the DataTable GridView1.DataSource = dt; GridView1.DataBind(); } // Store the DataTable in ViewState to retain the values ViewState["CurrentData"] = dt; } |
Note that we store the DataTable in ViewState to retain the data values associated within the DataTable and use that as our GridView DataSource when it post back to the server.
STEP 3:
Binding the GridView on Button_Click event.
protected void Button1_Click(object sender, EventArgs e) { // Check if the ViewState has a data assoiciated within it. If if (ViewState["CurrentData"] != null) { DataTable dt = (DataTable)ViewState["CurrentData"]; int count = dt.Rows.Count; BindGrid(count); } else { BindGrid(1); } TextBox1.Text = string.Empty; TextBox1.Focus(); } |
STEP 4:
Compile and run the application.
So when you type anything on each TextBoxes on the page and hit the Button, then the GridView will be populated with the data based on the TextBox values entered and retain its values on postback.
Technorati Tags:
ASP.NET,
GridView