Get return value from pressed button
Solution 1
Add a private variable in the form:
private object SelectedTag;
Add a button click handler:
private void Button_Click(object sender, EventArgs e) {
SelectedTag = ((Button)sender).Tag;
}
Assign the handler to each button you create:
..
buttonArray[i].OnClick += form.Button_Click;
..
Then in your static function, simply return form.SelectedTag
instead of the dialogresult.
Solution 2
You could call the same click event for all buttons. then in your handler:
private void ButtonClick(object sender, EventArgs args)
{
Button oButton = (Button) sender;
object data = oButton.Tag;
}
Arto Uusikangas
Program Developer in the middle of the dark forests in Småland, Sweden. Good skills with PHP, XSLT, XML and XSL-FO. Else, i engage in some golf in the summers and like movies...
Updated on June 25, 2022Comments
-
Arto Uusikangas almost 2 years
I have a form that pops up at a specific event. It draws up buttons from an array and sets the Tag value to a specific value. So if you are to press or click this button the function should return the Tag value.
How can I do this? And how do I know which button was clicked? At this moment the code returns DialogResult, but I want to return the Tag value from the function. How shall I modify my code so that it can do this?
public static DialogResult SelectBox(string title, string[] btnArray, string[] btnValueArray) { Form form = new Form(); Button[] buttonArray; buttonArray = new Button[5]; form.Text = title; for (int i = 0; i < btnArray.Length; i++) { buttonArray[i] = new Button(); buttonArray[i].Text = btnArray[i]; buttonArray[i].Tag = new int(); buttonArray[i].Tag = btnValueArray[i]; buttonArray[i].TabStop = false; buttonArray[i].Location = new System.Drawing.Point(0, i * 40); buttonArray[i].Size = new System.Drawing.Size(240, 40); } form.ClientSize = new Size(240, 268); form.Controls.AddRange(new Control[] { buttonArray[0], buttonArray[1], buttonArray[2] }); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; DialogResult dialogResult = form.ShowDialog(); return dialogResult; }
-
Oscar Mederos over 13 yearsWhat if there are more than 8 buttons? (DialogResult enum has 8 possible values)
-
Cody Gray over 13 years@Oscar: Yeah, if that's the case, you'll need to do a bit more work. Rarely (if ever) should a form contain more than 8 buttons.
-
Oscar Mederos over 13 yearsJust open Microsoft Outlook, Go to Tools > Options and you will see (only in the first tab) 13 ;)