tabs

Tuesday, October 29, 2013

Populating GridView with Textbox values

Many times in our applications we come across storing values, Names, and some other details and display them static or dynamically. We generally use a Gridview to populate them with our values entered in our form.
In this post I will explain you with a simple example on how to populate or store values in a grid view which displays the details statically in our webpage.
Let this be my HTML Code:
<html>
<head runat="server">
    <title>Populating Grid with Form Values</title>
</head>
<body>
    <form id="myForm" runat="server">
        <div>
            My Value 1:<asp:textbox id="txtVal1" runat="server"></asp:textbox>
            <br />
            My Value 2:<asp:textbox id="txtVal2" runat="server"></asp:textbox>
            <br />
            My Value 3:<asp:textbox id="txtVal3" runat="server"></asp:textbox>
            <asp:gridview id="myGrid" runat="server">
            </asp:gridview>
            <br />
            <asp:button id="btnSave" runat="server" onclick="btnSubmit_Click" text="submit" />
        </div>
    </form>
</body>
</html>
The above html generates a form with three textboxes and a submit button and a Gridview. When I enter some values in the textboxes and click the submit button the values get populated in the grid and displayed statically.
The logic behind generating a pattern for the grid and populating the details in it goes here:
Code Behind:
protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            if (myGrid.Rows.Count == 0)
            {
                dt = MakeTable();
 
            }
            else
            {
                dt = (DataTable)ViewState["dt"];
            }
            DataRow dr = dt.NewRow();
            dr[0] = txtVal1.Text;
            dr[1] = txtVal2.Text;
            dr[2] = txtVal3.Text;
            dt.Rows.Add(dr);
            myGrid.DataSource = null;
            myGrid.DataSource = dt;
            myGrid.DataBind();
            ViewState.Add("dt", dt);
        }
        DataTable MakeTable()
        {
            DataTable Mydt = new DataTable();
            DataColumn column1 = new DataColumn("column1");
            column1.DataType = System.Type.GetType("System.String");
            Mydt.Columns.Add(column1);
 
            DataColumn column2 = new DataColumn("column2");
            column2.DataType = System.Type.GetType("System.String");
            Mydt.Columns.Add(column2);
 
 
            DataColumn column3 = new DataColumn("column3");
            column3.DataType = System.Type.GetType("System.String");
            Mydt.Columns.Add(column3);
            return Mydt;
        }
On running this code we can see that the details from the textboxes get populated in the gridview and displayed on our web page.
Hope it helps you and especially for those who are fresh developers.

No comments:

Post a Comment