Loke Lindhardt Loke Lindhardt - 2 months ago 21
ASP.NET (C#) Question

Databind to a Repeater

I am having a really hard time wrapping my head around the use of datatables. There for i been trying to use them more active, now this is where my issue surface.

This code returns no errors but no data is bound to the repeater:

Page:

<asp:Repeater ID="RepeaterBrand" runat="server">
<ItemTemplate>
<p><%# Eval("products_name")%></p>
</ItemTemplate>
</asp:Repeater>


Codebehind:

protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["brand"] != null && !IsPostBack)
{

var Brand = (Request.QueryString["brand"]);

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT * FROM Table_Products WHERE products_brand = @Pr_brand", conn);
cmd.Connection = conn;
cmd.Parameters.Add("@Pr_brand", System.Data.SqlDbType.VarChar).Value = Brand;
DataTable dt = new DataTable();
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows && reader.Read())
{
dt.Load(reader);
RepeaterBrand.DataSource = dt;
RepeaterBrand.DataBind();
}
conn.Close();
}
}


I'm quite new to C# so i might need some visual aid to get this.

Thank you in advance.

I hope this might help anyone this is what i ended up with after JaydipJ showed me the syntax.

if (Request.QueryString["brand"] != null && !IsPostBack)
{

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
var Brand = (Request.QueryString["brand"]);
cmd.CommandText = "SELECT * FROM Table_Products WHERE products_brand = @Pr_brand";
cmd.Parameters.Add("@Pr_brand", System.Data.SqlDbType.VarChar).Value = Brand;

SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
RepeaterBrand.DataSource = dt;
RepeaterBrand.DataBind();

Answer

Don't read data from SQLDataReader. use it as it is to fill DataTable

if (reader.HasRows )
{
   dt.Load(reader);
   RepeaterBrand.DataSource = dt;
   RepeaterBrand.DataBind();
}
Comments