0

I want to add buttons dynamically on c sharp windows form. the no of buttons should be equal the no of records available in data table & i want to display the record whose button is clicked. could anybody help me?

2
  • 4
    What did you try so far? Commented Aug 13, 2012 at 6:37
  • for loop to the count of records available --> Button myButton = new Button(); --> myPanel.Controls.Add(myButton); ??? Commented Aug 13, 2012 at 6:39

2 Answers 2

2

In your case you need to create user control which will represent your item record on UI, create constructor which asspt your item and public event in this user control and add to your container like this.

myPanel.Controls.Add(new ItemRecordUserControl(item));

Probably you will need to use some specific containers instead of regular panel, something like System.Windows.Forms.FlowLayoutPanel.

User control will looks like:

public partial class ItemRecorUserControl : UserControl
{
    public event EventHandler<EventArgs> ActionButtonClicked;

    public void OnActionButtonClicked(object sender, EventArgs e)
    {
        if (this.ActionButtonClicked != null)
            this.ActionButtonClicked(sender, e);
    }

    public ItemRecorUserControl()
    {
        InitializeComponent();
    }

    public ItemRecorUserControl(ItemRecord item) : this()
    {
        // fill item data here to controls
    }

    private void btnAction_Click(object sender, EventArgs e)
    {
        this.OnActionButtonClicked(sender, e);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can add buttons like this :

for (int i = 0; i < YourDataTableItemsCount; i++)
   {
       Button b = new Button();
       b.Left = //Calculate Left
       b.Top = //Calculate Top
       b.Parent = this; 
       //Or
       this.Controls.Add(b);
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.