Wednesday, 29 May 2013

Create ListView control in Asp.net with c# code

Create ListView control in Asp.net with c# code
 

Step 1 : Create you asp.net website first and then create on .aspx page in your website.

Step 2 : Open .aspx design page .

Step 3 : Open Toolbox dialog box  View Menu => Toolbox option

Step 4 : Click on Data sub link in Toolbox and select List view control from list and drag and drop to the page where you want to display that control.

<asp:ListView ID="ListView1" runat="server"></asp:ListView>

Step 5 : This is default list view control.We can create Item templete

<asp:ListView ID="ListView1" runat="server">
        <ItemTemplate>
            <table>
                <tr>
                    <td>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("Age") %>'></asp:Label>
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:ListView>


Step 6 : Create one function will create dummy DataTable to bind data in ListView

  public  DataTable getDataForListView()
    {
        DataTable dt = new DataTable("Names");
        DataColumn dc1 = new DataColumn("Name");
        DataColumn dc2 = new DataColumn("Age");
        dt.Columns.AddRange(new DataColumn[] { dc1, dc2 });
        DataRow dr1 = dt.NewRow();
        dr1[0] = "Ahmed";
        dr1[1] = "27";
        DataRow dr2 = dt.NewRow();
        dr2[0] = "Peter";
        dr2[1] = "30";
        DataRow dr3 = dt.NewRow();
        dr3[0] = "John";
        dr3[1] = "20";
        DataRow dr4 = dt.NewRow();
        dr4[0] = "Ali";
        dr4[1] = "30";

        DataRow dr5 = dt.NewRow();
        dr5[0] = "Ali";
        dr5[1] = "30";


        DataRow dr6 = dt.NewRow();
        dr6[0] = "Ali";
        dr6[1] = "30";


        DataRow dr7 = dt.NewRow();
        dr7[0] = "Ali";
        dr7[1] = "30";

        dt.Rows.Add(dr1);
        dt.Rows.Add(dr2);
        dt.Rows.Add(dr3);
        dt.Rows.Add(dr4);
        dt.Rows.Add(dr5);
        dt.Rows.Add(dr6);
        dt.Rows.Add(dr7);
        return dt;
    }


Step 7 : Bind Data to ListView control

 ListView1.DataSource = getDataForListView();
ListView1.DataBind();


 Step 8 : This way you can access Listview control. We learn in lext post how to format list view control and how to access property of list view control.


No comments:

Post a Comment

Thank you for your interest .