Sibusiso Shongwe Sibusiso Shongwe - 10 days ago 6
ASP.NET (C#) Question

Adding ASP.Net Controls Dynamically

I have a stored procedure that returns a number of rows based on the number of records stored in the database, now I want to have a way of creating a

<div>
tag with controls containing values from that row, if there are 10 rows returned from the database, then 10
<div>
tags must be created
, I have the code below to fetch the results from the database but I don't know how to continue from here.

String sql = "exec dbo.spLoadCandidates @NationalID, @PostID";
SqlDataReader reader;
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@NationalID",TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@PostID,", DropDownList1.SelectedValue);
conn.Open();
reader = cmd.ExecuteReader();
while (reader.HasRows)
{
//Dynamic Data here
}
conn.Close();
}


update: Am using web forms to do this

Answer

You got several alternatives.

Alternative 1. Add a PlaceHolder to your aspx, and fill it with the contents you want.

<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>

Then you can add contents to this PlaceHolder from code behind.

String sql = "exec dbo.spLoadCandidates @NationalID, @PostID";
SqlDataReader reader;
using (SqlCommand cmd = new SqlCommand(sql, conn)) 
{
    cmd.Parameters.AddWithValue("@NationalID",TextBox2.Text.Trim());
    cmd.Parameters.AddWithValue("@PostID,", DropDownList1.SelectedValue);
    conn.Open();
    reader = cmd.ExecuteReader();
    while (reader.HasRows)
    {
         // Create div.
         var div = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");      
        createDiv.InnerHtml = "" // Fill with your content...
        // Add to placeholder.
        PlaceHolder1.Add(createDiv);
    }
    conn.Close();
}      

Alternative 2. Use a Repeater to your aspx.

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <div><%# Eval("Name") %></div>
    </ItemTemplate>
</asp:Repeater>

And your code behind:

// Some class to keep your info...
public class MyModel
{
    public string Name { get; set; }
}

And your code:

String sql = "exec dbo.spLoadCandidates @NationalID, @PostID";
SqlDataReader reader;
using (SqlCommand cmd = new SqlCommand(sql, conn)) 
{
    cmd.Parameters.AddWithValue("@NationalID",TextBox2.Text.Trim());
    cmd.Parameters.AddWithValue("@PostID,", DropDownList1.SelectedValue);
    conn.Open();
    reader = cmd.ExecuteReader();
    var list = new List<MyModel>();
    while (reader.HasRows)
    {
        var model = new MyModel();
        model.Name = "foo"; // Fill with your content...
        list.Add(model);
    }
    conn.Close();

    // Bind to repeater.
    Repeater1.DataSource = list;
    Repeater1.DataBind();
}      
Comments