简体   繁体   中英

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

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();
}      

Since you are using ASP.NET WebForms I suggest you to use Repeater .

but if you prefer to do it with code, here's a workaround:

    // Sample data
    var items = new string[] { "User1", "User2", "User3" };

    foreach (var item in items)
    {
        // Create a new div control for each item
        // You can create any ASP.NET WebForms control as well, such ASP.Net Label or etc
        System.Web.UI.HtmlControls.HtmlGenericControl divControl = 
        new System.Web.UI.HtmlControls.HtmlGenericControl("DIV") {
            ID = item,
            InnerHtml = item
        };

        // Add control to the page
        // You can also add control to a panel or any container control
        Controls.Add(divControl);
    }

You can use a Repeater control for rendering any custom markup for a collection of items. You can try this:

Markup:

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

Code behind: bind your Sql result to the Repeater control.

protected void Page_PreRender(object sender, EventArgs e)
{                        
    String sql = "exec dbo.spLoadCandidates @NationalID, @PostID";
    using (SqlCommand cmd = new SqlCommand(sql, conn)) 
    {
        cmd.Parameters.AddWithValue("@NationalID",TextBox2.Text.Trim());
        cmd.Parameters.AddWithValue("@PostID,", DropDownList1.SelectedValue);
        conn.Open();
        using(SqlDataReader reader = cmd.ExecuteReader())
        {
            Repeater1.DataSource = reader;
            Repeater1.DataBind();                
        };
        conn.Close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM