Populating card view from database in ASP.Net

Viewed 662

Net. I want something like a recyclerview where you have 1 card in the aspx file which keeps recurring according to the number of entries in the database. So if my database table has supposed 3 entries of a particular name then there should be 3 cards in the page.

Here's what I did till now: In my .aspx file:

<div class="item-card9">
<a href="info_page.aspx" class="text-dark">
  <h4 class="font-weight-semibold mt-1">
     <asp:Label ID="Label1" runat="server" >
        <%# uni_name %>
     </asp:Label>
  </h4>
</a>
</div>

and for my aspx.cs:-

    public string uni_name;
    SqlCommand cmd = new SqlCommand();

    //SQL connection here

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        cmd.CommandText = //select statement here
        cmd.Connection = con;
        SqlDataReader rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            uni_name = rd["name"].ToString();
        }
        this.DataBind();

        con.Close();
    }

With this as of now I'm only able to get 1 entry from my database, but I want it to keep recurring until the end of the database.

1 Answers

You need some kind of array to show:

CS

public List<string> Names { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    cmd.CommandText = //select statement here
    cmd.Connection = con;
    SqlDataReader rd = cmd.ExecuteReader();
    Names = new List<string>();
    while (rd.Read())
    {
        Names.Add(rd["name"].ToString());
    }
    this.DataBind();

    con.Close();
}

ASP

 <%foreach (var name in this.Names)
  {%>
       <p><%=name%></p>
   <%}%>

Update. If you have a complex object like

class MyObj
{
    public string ID;
    public string Name;
}

You still can use it here instead of string.

public List<MyObj> Items{ get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    cmd.CommandText = //select statement here
    cmd.Connection = con;
    SqlDataReader rd = cmd.ExecuteReader();
    Items = new List<MyObj>();
    while (rd.Read())
    {
        var item = new MyObj
        {
             Name = rd["name"].ToString(),
             Id = rd["id"].ToString()
        };
        Names.Add(item);
    }
    this.DataBind();

    con.Close();
}

Then use it like

 <%foreach (var item in this.Items)
  {%>
       <p><%=item.Id%> <%=item.Name%></p>
   <%}%>
Related