Alright, so I have a program where I have some textboxes added like this:
TextBox textbox = new TextBox();
textbox.Location = new Point(100, 100);
this.Controls.Add(textbox)
Just after this I create a button:
Button button = new Button();
button.Text = String.Format("Calculate");
button.Location = new Point(70, 70);
this.Controls.Add(button);
Because I am adding this in, I need to create my own event handler:
button.Click += new EventHandler(button_Click);
The problem I am having is referencing the textbox I created in the event handler I made.
Any help would be appreciated.
Use the Name property in order to find it:
textbox.Name = "myTextBox";
void button_Click(object sender, EventArgs e) {
if (this.Controls.ContainsKey("myTextBox")) {
TextBox tb = this.Controls["myTextBox"] as TextBox;
MessageBox.Show(tb.Text);
}
}
Just store a class-level reference to your text box so you can reference it from within your button event handler.
Another option is to store a reference to the TextBox in the Tag Property of your Button:
button.Tag = textbox;
Then you can retrieve in your Button Click Handler:
void button_Click(object sender, EventArgs e)
{
TextBox tb = (TextBox)((Button)sender).Tag;
MessageBox.Show(tb.Text);
}
Related
I have created a dynamic label on button click on Windows Form. And then on a right click on the label. I'm showing a context menu "cm". I obviously want to add functionality to the context menu items. But what I don't understand is how do I reference the "lbl" object inside the event handler? How can I edit the properties of the labels from inside the event handlers named MarkedImportant and EditLabel?
public void btnMonSub_Click(object sender, EventArgs e)
{
string s = txtMonSub.Text;
Label lbl = new Label();
lbl.Text = s;
lbl.Location = new System.Drawing.Point(205 + (100 * CMonSub), 111);
CMonSub++;
lbl.Size = new System.Drawing.Size(100, 25);
lbl.BackColor = System.Drawing.Color.AliceBlue;
this.Controls.Add(lbl);
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Mark Important", MarkImportant);
cm.MenuItems.Add("Edit", EditLabel );
lbl.ContextMenu = cm;
}
private void MarkImportant(object sender, EventArgs e)
{
// imp..
}
private void EditLabel(object sender, EventArgs e)
{
// edit..
}
Or is there a better way to do this? Like dynamically adding the event handler itself?
Thanks in advance.
The ContextMenu has a property called SourceControl and MSDN says it
Gets the control that is displaying the shortcut menu.
So your event handler could reach the ContextMenu from the MenuItem passed as the sender parameter in this way
private void MarkImportant(object sender, EventArgs e)
{
// Convert the sender object to a MenuItem
MenuItem mi = sender as MenuItem;
if(mi != null)
{
// Get the parent of the MenuItem (the ContextMenu)
// and read the SourceControl as a label
Label lbl = (mi.Parent as ContextMenu).SourceControl as Label;
if(lbl != null)
{
....
}
}
}
So I create dynamic labels in a loop, labels for a list of file folders in a directory.
i want, when you click on the label, the files within the label will display in a listbox. but i cannot get my event handler working, is it necessary to give my label a name as shown, i feel like i need the name for the event, but if the name is dynamic, the event name needs to be too and i cannot do that. also, i will need access to the labels properties within the event, so thats why i created an overloaded method, but regardless, clicking on the label does not do either of my event handlers. please advise, i'd appreciate it. here is whats in my loop and my event handlers
string str = lstMovieFolders[i];
Label lbl = new Label();
lbl.Name = "lbl" + str;
lbl.Location = new Point(25, intStartPoint);
lbl.Text = str;
lbl.Size = new Size(x, y);
lbl.Click += new EventHandler(lbl_Click);
grp.Controls.Add(lbl);
intStartPoint += 30;
public static void lbl_Click(object sender, EventArgs e)
{
MessageBox.Show("HELLOS");
}
public static void lbl_Click(object sender, EventArgs e, Label lbl)
{
MessageBox.Show("HELLO");
}
You can use sender parameter to get the current Label that triggers the event.You do not need an overload
public static void lbl_Click(object sender, EventArgs e)
{
var label = sender as Label;
if(label != null)
{
string text = label.Text;
}
}
I want to put on existing button new event handle. I have 9 buttons created in form and want to display each name when is clicked on it, but don't want to put on every button message manually.
How to accomplish that?
You can use the sender propperty of the EventHandler in order to do that. This example uses winforms buttons:
SomeButtonClicked(object sender, EventArgs e)
{
var button = sender as Button;
MessageBox.Show(button.Name);
}
And then you can add this event to multiple buttons i.e.:
button1.Click += new System.EventHandler(SomeButtonClicked);
button2.Click += new System.EventHandler(SomeButtonClicked);
button3.Click += new System.EventHandler(SomeButtonClicked);
You can code something like this
private void MainForm_Load(object sender, EventArgs e) {
...
// Assigning on click event, assuming that all your buttons are on the MainForm
foreach (Control ctrl in Controls) {
Button btn = ctrl as Button;
if (!Object.ReferenceEquals(null, btn))
btn.Click += onButtonClick;
}
...
// On click itself
private void onButtonClick(Object sender, EventArgs e) {
Button btn = sender as Button;
String name = btn.Name; // <- Or whichever property of the button you want
}
i have an application Windows Form where i created dynamic controls and i need program events like Keypress but i can't make it 'cause they don't know each other once they just exists in runtime. (i' Sorry: English by google Tradutor)
The problem appears to be that you are creating your dynamic variables locally:
ComboBox c1 = new Combobox();
TextBox t1 = new TextBox();
Changing jacqijvv's answer a bit to look more like what I believe you are trying to achieve. I'm also going to assume that you have multiple textbox/combobox pairs that are related to each other so you could store them in a dictionary object to retrieve them later in the event handler:
public partial class Form1 : Form
{
public Dictionary<TextBox, ComboBox> _relatedComboBoxes;
public Dictionary<ComboBox, TextBox> _relatedTextBoxes;
public Form1()
{
InitializeComponent();
_relatedComboBoxes = new Dictionary<TextBox, ComboBox>();
_relatedTextBoxes = new Dictionary<ComboBox, TextBox>();
TextBox textBox = new TextBox();
textBox.Text = "Button1";
textBox.KeyDown += textBox_KeyDown;
ComboBox comboBox = new ComboBox();
// todo: initialize combobox....
comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
// add our pair of controls to the Dictionaries so that we can later
// retrieve them together in the event handlers
_relatedComboBoxes.Add(textBox, comboBox);
_relatedTextBoxes.Add(comboBox, textBox);
// add to window
this.Controls.Add(comboBox);
this.Controls.Add(textBox);
}
void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox comboBox = sender as ComboBox;
TextBox textBox = _relatedTextBoxes[comboBox];
// todo: do work
}
void textBox_KeyDown(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
// find the related combobox
ComboBox comboBox = _relatedComboBoxes[textBox];
// todo: do your work
}
}
You can try the following code:
public partial class Form1 : Form
{
// Create an instance of the button
TextBox test = new TextBox();
public Form1()
{
InitializeComponent();
// Set button values
test.Text = "Button";
// Add the event handler
test.KeyPress += new KeyPressEventHandler(this.KeyPressEvent);
// Add the textbox to the form
this.Controls.Add(test);
}
// Keypress event
private void KeyPressEvent(object sender, KeyPressEventArgs e)
{
MessageBox.Show(test.Text);
}
}
This should work.
At my program i dynamicly add Buttons to my form
{
...
Button bt = new Button();
bt.Text = "bla bla";
bt.MouseClick += new MouseEventHandler(bt_MouseClick);
myPanel.Controls.Add(bt);
...
}
void bt_MouseClick(object sender, MouseEventArgs e)
{
TabPage _tab = new TabPage();
_tab.Text = ??? // I want to get the Button's text ! this.Text returns me the
//main form.Text
}
How can access my dynamic Buttons properties ? How can I understand whick button is
clicked either getting its text.
Thanks.
void bt_MouseClick(object sender, MouseEventArgs e)
{
TabPage _tab = new TabPage();
_tab.Text = ((Button)sender).Text;
}
When an EventHandler delegate is invoked, the sender parameter is the component that raised the event, and the e parameter is a subclass of EventArgs that provides any additional component/event specific information for the event.
Therefore you can establish which button the event fired on by casting the sender parameter to Button:
void bt_MouseClick(object sender, MouseEventArgs e)
{
var button = (Button)sender;
TabPage _tab = new TabPage();
_tab.Text = button.Text;
}