This
article will show you how you can bind a listview control from database of a
list collection in asp.net using c#.net.
So for this
article first we will create a new asp.net application and add the below code
into the page.
<form id="form1" runat="server">
<div>
<table widtrh="100%">
<tr>
<td>
<asp:ListView ID="ListView1"
runat="server">
<LayoutTemplate>
<table width="100%">
<tr style="background-color: gray;">
<th>Name</th>
<th>Class</th>
<th>Section</th>
<th>Marks</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server" id="listViewControlData">
<td><%# Eval("Name") %></td>
<td><%# Eval("Class") %></td>
<td><%# Eval("Section") %></td>
<td><%# Eval("Marks") %></td>
</tr>
</ItemTemplate>
</asp:ListView>
</td>
</tr>
</table>
</div>
</form>
|
In above code please check the highlighted part of the code. You have to add this piece of code. If you not add the below code you will get the below error, while binding the control.
Now lets
check the code to bind the listview control.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class LiteralHeilight :
System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindListControl();
}
}
///
/// Code to bind data to list
view control
///
public void BindListControl()
{
List<StudentData> _studentData = new List<StudentData>();
_studentData = GetStudentData();
ListView1.DataSource = _studentData;
ListView1.DataBind();
}
///
/// This function is used for getting the student data to bind
///
///
public List<StudentData> GetStudentData()
{
List<StudentData> _studentData = new List<StudentData>();
//Add some record to literal. You can access data from DB and store into the List
_studentData.Add(new StudentData { Name = "Rajesh", Class = 10, Marks = 70, Section = "A" });
_studentData.Add(new StudentData { Name = "Umesh", Class = 11, Marks = 80, Section = "B" });
_studentData.Add(new StudentData { Name = "Mark", Class = 5, Marks = 90, Section = "C" });
_studentData.Add(new StudentData { Name = "Max", Class = 12, Marks = 60, Section = "D" });
_studentData.Add(new StudentData { Name = "Joyti", Class = 11, Marks = 87, Section = "A" });
return _studentData;
}
}
public class StudentData
{
public string Name { get; set; }
public int Class { get; set; }
public string Section { get; set; }
public int Marks { get; set; }
}
}
|
In above
code I have created a list this list I have used to bind the listview control.
Now lets check the output.
0 comments:
Please let me know your view