One function for multiple Textbox WPF - c#

I have 5 textboxes that gets editable on double click.
Below is method i have written for one textbox.
private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
txtFirstLctrTime.IsReadOnly = false;
txtFirstLctrTime.Background = new SolidColorBrush(Colors.White);
txtFirstLctrTime.Foreground = new SolidColorBrush(Colors.Black);
}
Is there any way i can use same method for all text box instead of writing different method for all?? I am fairly new to programming

You can atach this handler to all textboxes. Then you check the sender, because that's the textbox you actually clicked:
private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var textBox = sender as TextBox;
textBox.IsReadOnly = false;
textBox.Background = new SolidColorBrush(Colors.White);
textBox.Foreground = new SolidColorBrush(Colors.Black);
}
You should look into MVVM and data binding thought, having click-handlers and code-behind has it's limits.

Attach same handler to all textboxes and use sender argument to get textbox instance which raised event:
private void MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.IsReadOnly = false;
textBox.Background = new SolidColorBrush(Colors.White);
textBox.Foreground = new SolidColorBrush(Colors.Black);
}

Yes, there is a way. Sender is a parameter which can tell You which controll fired this event. Look at my example below:
private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextBox tbWhichFiredThisEvent = sender as TextBox;
if(tbWhichFiredThisEvent != null)
{
tbWhichFiredThisEvent.IsReadOnly = false;
// ... etc.
}
}

Another option is to inherit from TextBox and implement your specific behavior on the OnDoubleClick method.
This way you can have this control on different views without repeated code.

Related

Combining Multiple Event Methods

Looking to refactor some application code. I have a GUI that has several of the same events that are reflected for different labels, textboxes, etc...
For example:
private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.BackColor = Color.LightCyan;
}
and
private void textBox2_Enter(object sender, EventArgs e)
{
textBox2.BackColor = Color.LightCyan;
}
I just assign these methods to the event on the object properties in Visual Studio. Is there an efficient way to combine multiple event methods to clean up the code? Thanks!
Define a single event like:
private void textBox_Enter(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
textBox.BackColor = Color.LightCyan;
}
and then assign that event to all your TextBox Enter event like:
textBox1.Enter += textBox_Enter; //Same event handler
textBox2.Enter += textBox_Enter; //Same event handler
If both event handlers do the same exact logic, as you probably have listed here, just create 1 event handler and assign it to both components.
private void TextBox_Enter(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null) {
textBox.BackColor = Color.LightCyan;
}
}
To elaborate slightly you can take this approach even when you want to perform different actions depending on the control that fired the event.
private void textBox_Enter(object sender, EventArgs e)
{
//Check if the sender is textBox1
if(ReferenceEquals(sender, textBox1))
{
//Perform action on textBox1
}
//Check if the sender is textBox2
if(ReferenceEquals(sender, textBox2))
{
//Perform action on textBox2
}
}

how to create events on dynamic `textboxes`

I managed to create textboxes that are created at runtime on every button click. I want the text from textboxes to disappear when I click on them. I know how to create events, but not for dynamically created textboxes.
How would I wire this up to my new textboxes?
private void buttonClear_Text(object sender, EventArgs e)
{
myText.Text = "";
}
This is how you assign the event handler for every newly created textbox :
myTextbox.Click += new System.EventHandler(buttonClear_Text);
The sender parameter here should be the textbox which sent the even you will need to cast it to the correct control type and set the text as normal
if (sender is TextBox) {
((TextBox)sender).Text = "";
}
To register the event to the textbox
myText.Click += new System.EventHandler(buttonClear_Text);
Your question isn't very clear, but I suspect you just need to use the sender parameter:
private void buttonClear_Text(object sender, EventArgs e)
{
TextBox textBox = (TextBox) sender;
textBox.Text = "";
}
(The name of the method isn't particularly clear here, but as the question isn't either, I wasn't able to suggest a better one...)
when you create the textBoxObj:
RoutedEventHandler reh = new RoutedEventHandler(buttonClear_Text);
textBoxObj.Click += reh;
and I think (not 100% sure) you have to change the listener to
private void buttonClear_Text(object sender, RoutedEventArgs e)
{
...
}
I guess the OP wants to clear all the text from the created textBoxes
private void buttonClear_Text(object sender, EventArgs e)
{
ClearSpace(this);
}
public static void ClearSpace(Control control)
{
foreach (var c in control.Controls.OfType<TextBox>())
{
(c).Clear();
if (c.HasChildren)
ClearSpace(c);
}
}
This should do the job :
private void button2_Click(object sender, EventArgs e)
{
Button btn = new Button();
this.Controls.Add(btn);
// adtionally set the button location & position
//register the click handler
btn.Click += OnClickOfDynamicButton;
}
private void OnClickOfDynamicButton(object sender, EventArgs eventArgs)
{
//since you dont not need to know which of the created button is click, you just need the text to be ""
((Button) sender).Text = string.Empty;
}

Can't refer to Text propery of textbox from TextChanged eventhandler

I have a problem with getting the Text value of a textbox in the TextChanged event handler.
I have the following code. (simplified)
public float varfloat;
private void CreateForm()
{
TextBox textbox1 = new TextBox();
textbox1.Location = new Point(67, 17);
textbox1.Text = "12.75";
textbox1.TextChanged +=new EventHandler(textbox1_TextChanged);
}
private void textbox1_TextChanged(object sender, EventArgs e)
{
varfloat = float.Parse(textbox1.Text);
}
I get the following error:'the name textbox1 does not exist in the current context'.
I probably made a stupid mistake somewhere, but I'm new to C# and would appreciate some help.
Thanks in advance!
You've declared textBox1 as a local variable within CreateForm. The variable only exists within that method.
Three simple options:
Use a lambda expression to create the event handler within CreateForm:
private void CreateForm()
{
TextBox textbox1 = new TextBox();
textbox1.Location = new Point(67, 17);
textbox1.Text = "12.75";
textbox1.TextChanged +=
(sender, args) => varfloat = float.Parse(textbox1.Text);
}
Cast sender to Control and use that instead:
private void textbox1_TextChanged(object sender, EventArgs e)
{
Control senderControl = (Control) sender;
varfloat = float.Parse(senderControl.Text);
}
Change textbox1 to be an instance variable instead. This would make a lot of sense if you wanted to use it anywhere else in your code.
Oh, and please don't use public fields :)
Try this instead :
private void textbox1_TextChanged(object sender, EventArgs e)
{
varfloat = float.Parse((sender as TextBox).Text);
}
Define the textbox1 out side CreateForm() at class level scope instead of function scope, so that it is available to textbox1_TextChanged event.
TextBox textbox1 = new TextBox();
private void CreateForm()
{
textbox1.Location = new Point(67, 17);
textbox1.Text = "12.75";
textbox1.TextChanged +=new EventHandler(textbox1_TextChanged);
}
private void textbox1_TextChanged(object sender, EventArgs e)
{
varfloat = float.Parse(textbox1.Text);
}
You have not added the textbox control to the form.
It can be done as
TextBox txt = new TextBox();
txt.ID = "textBox1";
txt.Text = "helloo";
form1.Controls.Add(txt);

How can i take dynamically created buttons' name when they are clicked?

I'm making a mahjong game and I'm totally new at C#, I wonder how i can take a button's name when it's clicked. All the buttons are created dynamically in the form.
public Button createButton(node x)
{
Button nButton;
nButton = new Button();
nButton.Name = x.info.ToString();
nButton.Text = x.info.ToString();
nButton.Width = 55;
nButton.Height = 75;
nButton.Visible = true;
if (x.isValid())
nButton.Enabled = true;
else
nButton.Enabled = false;
nButton.Click += new System.EventHandler(n1_click);
return nButton;
}
in the form i take buttons with this code
myButton = createButton(tp);
myButton.Location = new System.Drawing.Point(25 , 25);
this.Controls.Add(myButton);
The first argument to the event handler is the sender, you can cast that to a Button and then access the Name property.
Here is a small example of the event handler.
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
// Do something with button.Name
}
}
Edit: As Hans mentioned in the comments, using as could hide a potential bug. Using the as operator as in the example above will ensure that if you inadvertently wire this handler to an event of another control the code will handle it graciously and not throw an InvalidCastException, but there-in lies a problem as well, because this now silently fails you might not pickup a bug in your code. If the exception was thrown you would have realized there is a problem and been able to track it down. So the updated code would be something like this.
private void Button_Click(object sender, EventArgs e)
{
// If sender is not a Button this will raise an exception
Button button = (Button)sender;
// Do something with button.Name
}
With the following code you can get the button that was clicked
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
}
on the function which handles the click "n1_click"
private void n1_click(object sender, EventArgs e)
{
Button temp = (Button)sender;
string neededText = temp.Text;
}

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