我将转发器定义为
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%#Eval("name")%>
</ItemTemplate>
</asp:Repeater>
背后的代码是
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";
}
为什么它不绑定转发器中的数据?
答案 0 :(得分:3)
为什么要将数据读取器绑定到转发器?我建议你使用强类型对象。首先,定义一个代表您的数据的模型:
public class Student
{
public string Name { get; set; }
}
然后是一个获取这些学生的方法:
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"));
}
}
}
}
}
然后绑定转发器:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rep1.DataSource = GetStudents().ToArray();
rep1.DataBind();
}
}
并在视图中:
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:Repeater>
另请注意,转发器的名称为rep1
,因此您应该在后面的代码中使用该名称。
答案 1 :(得分:0)
您的转发器的ID为rep1
,而您正在数据绑定cdcatalog
。我想你的问题就在那里。这是cdcatalog
是什么?