ASP.net Repeater not binding values
I have a repeater defined as
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%#Eval("name")%>
</ItemTem开发者_C百科plate>
</asp:Repeater>
The code behind is as
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = @"Data Source=XXXXXX;Trusted_Connection=yes;database=master";
xconn.Open();
lbl1.Text = "Connected to SQL";
SqlCommand ycmd = new SqlCommand("select * from student",xconn);
SqlDataReader dr = ycmd.ExecuteReader();
cdcatalog.DataSource = dr;
cdcatalog.DataBind();
}
catch (Exception)
{
lbl1.Text= "Cannot connect to SQL";
}
Why does it not bind the data in the repeater?
Why are you binding data readers to a repeater? I would recommend you using strongly typed objects. So start by defining a model that will represent your data:
public class Student
{
public string Name { get; set; }
}
then a method to fetch those students:
public IEnumerable<Student> GetStudents()
{
using (var conn = new SqlConnection("Data Source=XXXXXX;Trusted_Connection=yes;database=master"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Students;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Student
{
Name = reader.GetString(reader.GetOrdinal("Name"));
}
}
}
}
}
and then bind the repeater:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rep1.DataSource = GetStudents().ToArray();
rep1.DataBind();
}
}
and in the view:
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:Repeater>
Also note that the name of the repeater is rep1
so that's what you should use in your code behind.
the ID of your repeater is rep1
whereas you are databinding cdcatalog
. I guess your problem is there. What is this cdcatalog
?
精彩评论