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

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

Related

C# how do I make my label from an label array disappear when clicked on?

My code makes 5 labels appear with a random .Left location, you can see it.
I want the particular label to disappear when I click on it, but I don't know how to tell it to my click void.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Label [] kubeliai = new Label [5];
int poz = 100;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < kubeliai.Length; i++)
{
kubeliai[i] = new Label();
Controls.Add(kubeliai[i]);
Random pos = new Random();
kubeliai[i].Top = 50;
kubeliai[i].Left = poz;
poz += pos.Next(50, 200);
kubeliai[i].BackColor = Color.Red;
kubeliai[i].Height = 20;
kubeliai[i].Width = 20;
kubeliai[i].Click += new EventHandler(kubelio_clickas);
}
}
void kubelio_clickas (object sender, EventArgs e)
{
}
}
The instance of "clicked" label is in sender parameter:
void kubelio_clickas (object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (clickedLabel != null) {
clickedLabel.Visible = false;
}
}
Because in .NET Event Handlers by default use object as type of sender you have to cast it to Label first.
I want the particular label to disappear when I click on it
Just set the label's .Visible property to false:
void kubelio_clickas (object sender, EventArgs e)
{
if (sender is Label)
((Label)sender).Visible = false;
}
The object sender is a reference to the object which fired the event. So basically, the sender is the object you are looking for.
You just need to set it invisible:
((Label)sender).Visible = false;

One function for multiple Textbox WPF

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.

Creating Event Handlers

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

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

C# textbox access

I'm having an irritating problem with textbox. I enter data in one textbox and with the click of the button i need to display result in another textbox. I really dont know why my method wouldnt work. I dont get any errors, but it wouldnt display the result. Thanks!
All of the textboxes are dynamically created during the run time.
here is the code:
private void button2_Click(object sender, EventArgs e)
{
TextBox tbox8 = new TextBox();
tbox8.Name = "textBox8";
tbox8.Location = new System.Drawing.Point(54 + (0), 55);
tbox8.Size = new System.Drawing.Size(53, 20);
this.Controls.Add(tbox8);
tbox8.BackColor = System.Drawing.SystemColors.InactiveCaption;
tbox8.TextChanged += new EventHandler(tbox8_TextChanged);
TextBox tbox9 = new TextBox();
tbox9.Name = "textBox9";
tbox9.Location = new System.Drawing.Point(54 + (60), 55);
tbox9.Size = new System.Drawing.Size(53, 20);
this.Controls.Add(tbox9);
tbox9.BackColor = System.Drawing.SystemColors.InactiveCaption;
tbox9.TextChanged += new EventHandler(tbox9_TextChanged);
}//button_click
//input data into texbox8
TextBox tbox;
double var1;
private void tbox8_TextChanged(object sender, EventArgs e)
{
tbox = sender as TextBox;
var1 = Convert.ToDouble(tbox.Text);
}
//display the result in textbox9
TextBox tbox2;
private void tbox9_TextChanged(object sender, EventArgs e)
{
tbox2 = sender as TextBox;
}
//perform calculation and on button click display data on referenced textbox
private void button3_Click(object sender, EventArgs e)
{
double result2 = var1 * 2;
if( tbox2 != null)
{
tbox2.Text = result2.ToString();
}
}
Here is your code with the unnecessary bits commented out, and some new lines added:
TextBox tbox8 = new TextBox(); //make it a member variable
TextBox tbox9 = new TextBox(); //same for this one
private void button2_Click(object sender, EventArgs e)
{
tbox8.Name = "textBox8";
tbox8.Location = new System.Drawing.Point(54 + (0), 55);
tbox8.Size = new System.Drawing.Size(53, 20);
this.Controls.Add(tbox8);
tbox8.BackColor = System.Drawing.SystemColors.InactiveCaption;
tbox8.TextChanged += new EventHandler(tbox8_TextChanged);
tbox9.Name = "textBox9";
tbox9.Location = new System.Drawing.Point(54 + (60), 55);
tbox9.Size = new System.Drawing.Size(53, 20);
this.Controls.Add(tbox9);
tbox9.BackColor = System.Drawing.SystemColors.InactiveCaption;
tbox9.TextChanged += new EventHandler(tbox9_TextChanged);
}//button_click
//input data into texbox8
//TextBox tbox;
double var1;
private void tbox8_TextChanged(object sender, EventArgs e)
{
//tbox = sender as TextBox;
var1 = Convert.ToDouble(tbox8.Text);//tbox8
}
//display the result in textbox9
//TextBox tbox2;//tbox2 is actually tbox9 anyway
private void tbox9_TextChanged(object sender, EventArgs e)
{
// tbox2 = sender as TextBox;//so we don't need a tbox2
//do something
}
//perform calculation and on button click display data on referenced textbox
private void button3_Click(object sender, EventArgs e)
{
double result2 = var1 * 2;
//if( null != tbox9 )
//{
tbox9.Text = result2.ToString(); //changed to tbox9
//}
}
However, this still has problems. What happens when the user clicks button2 more than once?
Assuming tbox8 (try using meaningful names BTW) is the one that the text is supposed to be entered and tbox14 is where you expect the output to go, why do you only set the tbox2 variable in the TextChanged event of tbox14? You code probably isn't working because tbox2 is always null, because you never execute the TextChanged event for tbox14. And why are you using the variable tbox2 instead of just using tbox14 anyway?
Also, parsing the text in the TextChanged event of tbox8 is probably the wrong place to do it. The TextChanged event will fire on every keystroke. Why not just do it once in the button3 Click handler? Or, do it when it loses focus.
Try this (note: not that this isn't still crappy code). First, get rid of all the TextChanged events, then:
private void button3_Click(object sender, EventArgs e)
{
var1 = Convert.ToDouble(tbox8.Text);
double result2 = var1 * 2;
tbox14.Text = result2.ToString();
}
Something like this should work assuming result * 2 doesn't cause an arithmetic overflow for a double. If the value entered into tbox8 can't be parsed into a double, the result displayed in tbox9 after clicking button3 will be 0.
Since I'm not using any of the events of the TextBoxes, I don't need to create handlers for them. I'm also disabling button2 after it is clicked so that it can't be clicked again.
If you need to click button2 again, you'll need to enable it from another button event handler or something so that you have the chance to remove tbox8 and tbox9 from the this.Controls collection before enabling it (button2) to prevent the application from attempting to create additional copies of them.
private void button2_Click(object sender, EventArgs e) {
button2.Enabled = false;
TextBox tbox8 = new TextBox();
tbox8.Name = "textBox8";
tbox8.Location = new System.Drawing.Point(54 + (0), 55);
tbox8.Size = new System.Drawing.Size(53, 20);
this.Controls.Add(tbox8);
tbox8.BackColor = System.Drawing.SystemColors.InactiveCaption;
TextBox tbox9 = new TextBox();
tbox9.Name = "textBox9";
tbox9.Location = new System.Drawing.Point(54 + (60), 55);
tbox9.Size = new System.Drawing.Size(53, 20);
this.Controls.Add(tbox9);
tbox9.BackColor = System.Drawing.SystemColors.InactiveCaption; }
private void button3_Click(object sender, EventArgs e) {
double result = 0;
double.TryParse(tbox8.Text, out result);
tbox9.Text = (double)(result * 2).ToString(); }

Categories