on Leave a Comment

Bind DataTable Data In GridView

Here I will Explain how to bind Datatable data into gridview

First we take one gridview in the aspx page. in this gridview we bind student table data.it has three column sid,sname,marks.
Aspx page
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
            CellPadding="3" GridLines="Vertical" >      
            <AlternatingRowStyle BackColor="#DCDCDC" />
            <Columns>        
                <asp:BoundField DataField="sid" HeaderText="Id" ReadOnly="True" />
                <asp:BoundField DataField="sname" HeaderText="Name" />
                <asp:BoundField DataField="marks" HeaderText="Marks" />
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>        
        </asp:GridView>

Now add following namespaces in codebehind
Aspx.cs Page
using System.Data;
using System.Data.SqlClient;
After that add following code in code behind

 static SqlConnection con = new SqlConnection("Data Source=MALVIK-PC\\SQLEXPRESS;Initial Catalog=malvik;Integrated Security=True;Pooling=False");
    static SqlDataAdapter da = new SqlDataAdapter("select *from student", con);
    DataTable dt = new DataTable();
 protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            da.Fill(dt);
            ViewState["dt"] = dt;
            bind();
        }
        else
        {
            dt = (DataTable)ViewState["dt"];
        }
    }
    protected void bind()
    {
        gv.DataSource = dt;
        gv.DataBind();
    }

0 comments:

Post a Comment

aspdotnet-learn. Powered by Blogger.