on Leave a Comment

How to Bind Data in Datalist

Here,aspx  page  design
<div>
        <asp:DataList ID="dl" runat="server">
            <HeaderTemplate>
                <table>
                    <tr>
                        <td width="100px">
                            Id:
                        </td>
                        <td width="100px">
                            Name:
                        </td>
                        <td width="100px">
                            Marks:
                        </td>
                    </tr>
                </table>
            </HeaderTemplate>
            <ItemTemplate>
                <table>
                    <tr>
                        <td width="100px">
                            <asp:Label ID="lblid" runat="server" Text='<%#Eval("sid") %>'></asp:Label>
                        </td>
                        <td width="100px">
                            <asp:Label ID="lblname" runat="server" Text='<%#Eval("sname") %>'></asp:Label>
                        </td>
                        <td width="100px">
                            <asp:Label ID="lblmarks" runat="server" Text='<%#Eval("marks") %>'></asp:Label>
                        </td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:DataList>
    </div>
Now add the following namespaces in codebehind and After that write the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
     static SqlConnection con = new SqlConnection("Data Source=\\SQLEXPRESS;Initial Catalog;Integrated Security=True;Pooling=False");
     static SqlDataAdapter da = new SqlDataAdapter("select *from student",con);
     SqlCommandBuilder cmdb = new SqlCommandBuilder(da);
     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()
    {        
        dl.DataSource = dt;
        dl.DataBind();     
    }

0 comments:

Post a Comment

aspdotnet-learn. Powered by Blogger.