infolink

Saturday, 25 August 2012

Show data in grid view in ASP.NET

This tutorial is about  the grid view control. grid view Control is a very powerful control. it is a table structure where data show in the rows and columns.
Here we can see how to show data in the grid view when user press the button.
When the user Click on the button every time a new row will added in the grid view.
Below mention code is used for this purpose.

Step1:

In the Default.aspx page write these code:



<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div>
                <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
                <br /><br /><br />
                <asp:GridView ID="GridView1" runat="server">
                </asp:GridView>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    
    </form>
</body>
</html> 


Step2:

In the Default.aspx.cs file write following code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            datastructure();

        }
    }
    private void datastructure()
    {
        DataTable dtC = new DataTable();
        dtC.Columns.Add("Name");
        dtC.Columns.Add("Father");
        ViewState["dt"] = dtC;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)ViewState["dt"];
        DataRow dtRow = dt.NewRow();
        dtRow["Name"] = "ABC";
        dtRow["Father"] = "XYZ";
        dt.Rows.Add(dtRow);
        dt.AcceptChanges();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

----------------------------------------------------------------
Try this your self. Hope this will help you.

No comments:

Post a Comment