Question

The following button provides the exact functionality I require, but it must be done programmatically as I will be making more than one based on some variables, but the latter I can figure out if I can just create the button below as a starter:

<asp:Button runat="server" OnCommand="Load_Items" CommandArgument="1" text="Submit" />

More information on what I've been doing here.

Edit:

I have looked at questions like this, but don't see where to go from Button btnSave = new Button(); to seeing a button on the page. Also, most questions I've found seem to go about using C# to handle clicking, but I want to have an OnCommand property to handle it.

If I do the following and search using the developer tools for "btn", I get no results.

Button btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save";
btnSave.CssClass = "btn";
Was it helpful?

Solution

Here is how you create a Button with Command event.

Once it is created, you need to find a way of displaying it. The following example uses PlaceHolder; you can also substitute with Panel if you want.

ASPX

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

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 5; i++)
    {
        var button = new Button
        {
            ID = "Button" + i,
            CommandArgument = i.ToString(),
            Text = "Submit" + i
        };
        button.Command += Load_Items;
        PlaceHolder1.Controls.Add(button);
    }
}

private void Load_Items(object sender, CommandEventArgs e)
{
    int id = Convert.ToInt32(e.CommandArgument);
    // Do something with id
}

OTHER TIPS

You need a container control on your page. Try an asp panel for example. Then in your codebehind you do panel.controls.add(btnSave); And don't forget to do it on every site load. http://support.microsoft.com/kb/317515/en-us

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top