Shalvin Interests

Tuesday, January 24, 2012

Asp .Net ListView with Ado .Net Code

I am going to explore Asp .Net ListView with Ado .Net code. There are plenty of Asp .Net ListView articles out there explaining data binding with SqlDataSource. Unfortunately SqlDataSource can only  be used with toy projects.

<appSettings>
    <add key="ConnectionString" value="Data Source=.\sqlexpress;Initial Catalog=ContactManagement;Integrated Security=True"/>
  </appSettings>

I am using a table called ContactGroups with two fields GroupId and GroupName of which GroupId is an identity column.

I am creating its corresponding entity class called EContactGroups.

public class EContactGroups
{
    public int GroupId { get; set; }
    public string GroupName { get; set; }
}


In another class I am creating a method named GetGroups that will return an List of EContactGroups entity.
using System.Data.SqlClient;

public class BContactGroups
{
    SqlDataReader dr;
    SqlCommand cmd;
    DbConnect dbc = new DbConnect();
    public List<EContactGroups> GetGroups()
    {
        List<EContactGroups> glECG = new List<EContactGroups>();
        dbc.Open();
        cmd = new SqlCommand("select * from ContactGroups", dbc.cnn);
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            EContactGroups oECG = new EContactGroups();
            oECG.GroupId = Convert.ToInt32(dr["GroupId"]);
            oECG.GroupName = dr["GroupName"].ToString();

            glECG.Add(oECG);
        }
        dr.Close();
        return glECG;
    }
}


<asp:ListView ID="ListView1" runat="server">
    <LayoutTemplate>
        <table>
        <thead>
            <tr>
                
                <th>Group Id</th>
                <th>Group Name</th>
            </tr>                
        </thead>
        <tbody>
            <asp:Placeholder 
                id="itemPlaceholder" 
                runat="server" />
        </tbody>
        </table>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
            <td><%# Eval("GroupId") %></td>
            <td><%# Eval("GroupName") %></td>
        </tr>
    </ItemTemplate>
    <EmptyDataTemplate>
        No records found
    </EmptyDataTemplate>
</asp:ListView>


public partial class _Default : System.Web.UI.Page
{
    BContactGroups objCG = new BContactGroups();
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGroups();
    }

    private void BindGroups()
    {
        var g = (from p in objCG.GetGroups()
                 select p).ToList();

        ListView1.DataSource = g;
        DataBind();
    }
}