Help adding buttons at runtime...

  • Thread starter Thread starter Doug Slocum
  • Start date Start date
D

Doug Slocum

Hi,
I'm using ASP.NET. I need help adding new buttons to my web page at run
time on the server side prior to sending to the client.
As the web form is loading, I won't know in advance how many buttons I'll
need or the properties for each until I read a database.
For each new button, I need to assign the text, name ('id' for later
reference), and set the code-behind to handle the events for each.
I hope I'm clear. Could someone suggest some code that will help me please?
Thanks,
Doug
 
you can write like this..keep the loop based on your database data.

for(int i=0; i<10; i++)
{
Button btn = new Button();
btn.ID = "Button" + i.ToString();
btn.Text = "Button" + i.ToString();
btn.CommandName = "Button" + i.ToString();
btn.Click += new EventHandler(btn_Click);
}

private void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.CommandName == "")
{
}
}

make sure that you always add these controls irrespective of IsPostBack..you
can put them in page_load.

Av.
 
Av,

In VB.NET I've tried :
----
Try

Dim i As Integer

For i = 0 To 9

Dim btn As New Button

btn.ID = "button" & i.ToString

btn.Text = "button" & i.ToString

btn.CommandName = "button" & i.ToString

Next

Catch ex As Exception

MsgBox(ex.Message)

End Try

-------------------

....This runs without errors but no buttons show in the browser. Also, there
is no btn.Click that I can find.

What could be wrong?

Doug
 
Back
Top