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?
-
4What did you try so far?Fredrik Mörk– Fredrik Mörk2012-08-13 06:37:35 +00:00Commented Aug 13, 2012 at 6:37
-
for loop to the count of records available --> Button myButton = new Button(); --> myPanel.Controls.Add(myButton); ???CptSupermrkt– CptSupermrkt2012-08-13 06:39:57 +00:00Commented Aug 13, 2012 at 6:39
Add a comment
|
2 Answers
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);
}
}