1

I have a repeater defined as

<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%#Eval("name")%>
</ItemTemplate>
</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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

the ID of your repeater is rep1 whereas you are databinding cdcatalog. I guess your problem is there. What is this cdcatalog?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.