Make a control dynamic recognize another - c#

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.

Related

How to create the event handler for editing dynamic labels in C#?

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)
{
....
}
}
}

referencing programatically added controls in a different event handler?

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);
}

WPF C# Drag and Drop

Basically i am doing a drag and drop using textbox and labels , by dragging a label to a textbox . Textboxes and Labels are created in same for loop .
I have dynamically created textboxes ( textbox is the drop target) like this :
TextBox tbox = new TextBox();
tbox.Width = 250;
tbox.Height = 50;
tbox.AllowDrop = true;
tbox.FontSize = 24;
tbox.BorderThickness = new Thickness(2);
tbox.BorderBrush = Brushes.BlanchedAlmond;
tbox.Drop += new DragEventHandler(tbox_Drop);
if (lstQuestion[i].Answer.Trim().Length > 0)
{
wrapPanel2.Children.Add(tbox);
answers.Add(lbl.Content.ToString());
MatchWords.Add(question.Content.ToString(), lbl.Content.ToString());
}
I have also dynanmically create labels ( label is the drag target) like this :
Dictionary<string, string> shuffled = Shuffle(MatchWords);
foreach (KeyValuePair<string, string> s in shuffled)
{
Label lbl = new Label();
lbl.Content = s.Value;
lbl.Width = 100;
lbl.Height = 50;
lbl.FontSize = 24;
lbl.DragEnter += new DragEventHandler(lbl_DragEnter);
lbl.MouseMove += new MouseEventHandler(lbl_MouseMove);
lbl.MouseDown +=new MouseButtonEventHandler(lbl_MouseDown);
// lbl.MouseUp +=new MouseButtonEventHandler(lbl_MouseUp);
dockPanel1.Children.Add(lbl);
}
I have 2 issues here .
1st . I am using tbox.drop event to display MessageBox.Show( something ) ; to display a messagebox when the drag target is being drop but it doesn't work .
here is my code :
private void tbox_Drop(object sender, DragEventArgs e)
{
MessageBox.Show("Are you sure?");
}
Second , i also want to clear the tbox.Text when the drag target is dropped because i might have other drag target dropped into the tbox previously. So i want to clear the tbox.Text and drop the drag target everytime when i drag the target to textbox .
How do i do that? i am stucked at which event i should use for this and how do i access tbox from those event handlers ?
It worked for me.
private void lbl_MouseDown(object sender, MouseButtonEventArgs e)
{
Label _lbl = sender as Label;
DragDrop.DoDragDrop(_lbl, _lbl.Content, DragDropEffects.Move);
}
You do not need MouseMove and DragEnter events for Label if you are using them just for Drag purpose.
Replace Drop event with PreviewDrop for TextBox as shown below:
tbox.Drop += new DragEventHandler(tbox_Drop);
with this
tbox.PreviewDrop += new DragEventHandler(tbox_PreviewDrop);
private void tbox_PreviewDrop(object sender, DragEventArgs e)
{
(sender as TextBox).Text = string.Empty;
}
The TextBox you want to drag(add mousedown event)
private void dragMe_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBox tb = sender as TextBox;
// here we have pass the textbox object so that we can use its all property on necessary
DragDrop.DoDragDrop(tb, tb, DragDropEffects.Move);
}
The TextBox on which you want to drop(add drop event and also you have to check the marked as allowdrop checkbox)
private void dropOnMe_Drop(object sender, DragEventArgs e)
{
TextBox tb= e.Data.GetData(typeof(TextBox)) as TextBox;
// we have shown the content of the drop textbox(you can have any property on necessity)
dropOnMe.Content = tb.Content;
}

Get name of control when mouse hovers over it C#

I am adding ComboBoxes dynamically at runtime as shown below.
The problem that I am having is that i do not know which of the comboboxes the user is using.
For eg. The user decides to add 5 comboBoxes to the form, and then goes to the first comboBox,and selects a value, I need to retrieve the value of that comboBox.
What the below code is doing - My approach
I am adding a comboBox to a FlowlayoutPanel and the retrieve its name based on the mouse co-ordinates.... this by the way is not working... and I have no idea what to do.
Any help is greatly appreciated.
public partial class Form1 : Form
{
int count = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
count += 1;
ComboBox cb = new ComboBox();
cb.Name = count.ToString();
cb.MouseHover += new EventHandler(doStuff);
Label lb = new Label();
lb.Text = count.ToString();
flowLayoutPanel1.Controls.Add(cb);
flowLayoutPanel1.Controls.Add(lb);
}
public void doStuff(object sender, EventArgs e)
{
label1.Text = flowLayoutPanel1.GetChildAtPoint(Cursor.Position).Name;
}
}
}
You could try:
cb.SelectionChangeCommitted += selectionChangedHandler
...
void selectionChangedHandler(object sender, EventArgs e) {
ComboBox cb = (ComboBox)sender;
label1.Text = cb.Name;
// Do whatever else is needed with the combo box
}
The SelectionChangeCommitted event is "raised only when the user changes the combo box selection", which sounds like what you're after.
The combobox that raised the event in your doStuff-eventhandler is in the sender-parameter. Try casting it to a checkbox likte this:
ComboBox boxThatRaisedTheEvent = (ComboBox)sender;
string text = ((ComboBox)this.GetChildAtPoint(pt)).Text;
public void DoStuff(object sender, EventArgs e)
{
var comboBox = sender as ComboBox;
var name = (comboBox != null ? comboBox.Name : null);
}
this code casts the 'sender' parameter to a ComboBox object and if the cast is done correctly assings the ComboBox name to the string 'name', otherwise 'name' is null.
Tip: The C# coding style suggests that method names should start with capitalized letter.
You can try something like:
flowLayoutPanel1.Controls.OfType<ComboBox>().FirstOrDefault(cb => cb.Name.Equals(NAME_OF_COMBOBOX))
Or better:
ComboBox box = (ComboBox)sender;

Dynamicly added Controls [e.g Button] : How to add events and Access

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;
}

Categories