Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create buttons dynamically to call method and pass in parameter

Tags:

c#

asp.net

I have a dictionary with a key value pair and need to loop through the pairs and create a button for each one and wire up the button to call a method DisplayDocument(string Id) and pass in the Key as a parameter.

Here's what I have so far.

        // test data
        var documents= new Dictionary<string,string>();
        documents.Add("69110","Diploma");
        documents.Add("76404", "Licensure");


        foreach (KeyValuePair<string, string> item in documents)
        {

            MyStringBuilder=MyStringBuilder.Append(item.Value + "   " + item.Key + "<br />"); 

        }
        printFaxDocuments.InnerHtml = MyStringBuilder.ToString();

What i want to do is print out the document Key and Value and then a button that the use can click to view the document. I have the method built to view the document and it requires the Key value to be passed in. How can I do this?

I'm not sure how to intersperse the button in the text data. I need to write out the key and value add the button add a "<br/>" and then do the same thing again for the next item in the dictionary.

like image 791
Ronald McDonald Avatar asked Oct 20 '11 18:10

Ronald McDonald


1 Answers

Below I have created the Button controls in the OnInit method and assigned each of them the same Click event handler.

The Key is stored in the Buttons CommandArgument property which is retrieved in the event handler and passed to the DisplayDocument method.

protected override void OnInit(EventArgs e)
{
    // test data
    var documents = new Dictionary<string, string>();
    documents.Add("69110", "Diploma");
    documents.Add("76404", "Licensure");

    foreach (KeyValuePair<string, string> item in documents)
    {
        Button button = new Button();
        button.Text = string.Format("Button: {0}", item.Key);
        button.CommandArgument = item.Key;
        button.Click += ButtonClicked;

        ButtonContainer.Controls.Add(button);
    }

    base.OnInit(e);
}

protected void ButtonClicked(object sender, EventArgs e)
{
    Button button = (Button) sender;
    string id = button.CommandArgument;

    DisplayDocument(id);
}

private void DisplayDocument(string id)
{
    //Do something
}

Edit

You are probably better off using CSS to set the layout for the Buttons.

Try adding the following CSS class to the head of your page (or stylesheet file)

<style type="text/css">
    .stacked-button
    {
        display:block;
    }
</style>

And then add the following to the button creation code:

button.CssClass = "stacked-button";

You can then add to the CSS class as required to modify the layout (margins etc.)

Hope this helps.

like image 184
jdavies Avatar answered Oct 02 '22 18:10

jdavies