create buttons dynamically c#

Posted on 2014-07-31
Last Modified: 2014-08-03
List of items from a stored procedure sp1 with one parameter @Region (linked to Session["RegionID"]):

PK   Title      Region
1       A           1
2       B            1

returns list of PKs and Titles.

In a <td> tag, I hope to create number of buttons dynamically (one per title) with title as button caption (the returned list has 3 to 15 titles in it depending on the region value).

Question: Would you please give me something to get started with this?

Thank you.
Question by:Mike Eghtebas
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
LVL 23

Accepted Solution

Jens Fiederer earned 350 total points
ID: 40233248
Let's say you have your captions in a variable q.

In the <td> you have an asp:Panel named container.

 foreach (var name in q)
                Button b = new Button { Text = name };

Open in new window

You might want to set the buttons' Click events to do something useful as well.
LVL 34

Author Comment

by:Mike Eghtebas
ID: 40233592
Hi Jens,

Good direction resulting in good progress. As shown on the attached image, the buttons do not sit inside the panel.

Q1: How can I make the buttons to be inside the panel in two columns and as many rows necessary.
Q2: Could you please take a look at my code and improve its syntax. I am sure this could be done much cleaner.

It is desirable the buttons to be 90px wide x 40px high.

Shortly, I will add a question requesting some help in adding OnClick event(s) for the buttons.

We could have only one event for all of the buttons if we could somehow transmit PK field of the captions to the event. The PK is 2-digit first column on the image.

Thank you,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class medCtrList : System.Web.UI.Page

    static Panel myPanel2 = new Panel();

    protected void Page_Load(object sender, EventArgs e)
        Session["Region"] = "Region 1";
         Panel  myPanel = (Panel)this.FindControl("Panel1");
         myPanel2 = myPanel;

    static void ReadButtons()
        using (SqlConnection connection = new SqlConnection("Data Source=USER-PC;Initial Catalog=ROD_July18;Integrated Security=True"))
            // Create the command and set its properties.
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandText = "SELECT t0... Sort DESC";
            command.CommandType = CommandType.Text;

            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
                while (reader.Read())
                    string btnCaption = "";
                    btnCaption = reader.GetString(1);
                // so something else
    static void makeButtonFor(string caption)
        Button b = new Button { Text = caption };

Open in new window

LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 150 total points
ID: 40233642
You will need to use styling on the container to control the width and force to wrap into two columns. If you want the ID associated with the control then you will need to embed it in the controls ID somewhere, as buttons don't have properties for storing additional information;

Say you had markup like:
        div { width: 200px; }
        input[type="submit"] { width: 90px; height: 40px; }

    <div id="container" runat="server">


Open in new window

Then the code could be:
while (reader.Read())
     int id = reader.GetInt32(0);
     string btnCaption = reader.GetString(1);
     makeButtonFor(id, btnCaption);

private void makeButtonFor(int id, string caption)
        Button b = new Button 
             ID = "Button"+id.ToString(),
             Text = caption 

Open in new window

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

LVL 23

Expert Comment

by:Jens Fiederer
ID: 40234477
I would have to see the markup rather than just the code-behind to see why you are adding buttons to the wrong panel.

You don't HAVE to use a single panel, although that is the quickest way to program can force columns using CSS as above, or you could construct a table and add the buttons to specific cells in that table if you prefer....or you could bind to a Repeater.

There are really lots of possibilities, and you can always check the "sender" in your event handler to see which button was pressed.

With the code page being
                <asp:Label runat="server" ID="result" />
                <asp:Repeater runat="server" ID="rpt">
                                <asp:Button  runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Text") %>' OnClick="Unnamed_Click" />

                                <asp:Button runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Text2") %>' OnClick="Unnamed_Click" />


Open in new window

code behind like the below will set the label to the text of whichever button you pressed (assuming "all" is a list of titles):
            var list = new List<object>();
            foreach (var i in all)
                list.Add(new { Text = i, Text2 = i + "foo" });

            rpt.DataSource = list;

Open in new window

LVL 23

Expert Comment

by:Jens Fiederer
ID: 40234481
Of course, this allows the REPEATER to construct the table ... there is nothing to stop you from creating an asp:Table in code behind and adding rows and cells and buttons to suit exactly what you want.

If you prefer to use CSS for the layout (which, if the reason for columns is visual rather than functional, is good style) and can assume HTML5 you could also use the new flexbox feature.
LVL 34

Author Closing Comment

by:Mike Eghtebas
ID: 40238296
Thank you very much.

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question