Updating a textbox using no input controls - c#

I have a windows form application which consists of a bunch of controls, but more specifically, two textBoxes. One of them is read only. The read only textBox value is supposed to be the same as the textBox that the user can type into.
So if the user types "Hello World" into textBox A, the value in textBox B should be automatically updated to "Hello World".
How do I go about doing this? I know I just need to set the text values, I'm just not sure where I place the code to get it done automatically rather than executed when a button is click or something along those lines.

TextChanged event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text;
}

It sounds like you want something like:
writableTextBox.TextChanged += delegate {
readonlyTextBox.Text = writableTextBox.Text;
};
In other words, whenever the text in one textbox changes, update the other. This uses the Control.TextChanged event.

If you want textBoxB to be updated as soon as the text of textBoxA is changed (i.e immediately after the user press a key in textBoxA) the event is TextChanged:
this.textBoxA.TextChanged += new System.EventHandler(this.textBoxA_TextChanged);
private void textBoxA_TextChanged(object sender, EventArgs e)
{
textBoxB.Text = textBoxA.Text;
}
If you prefer to update the text in textBoxB only after the user has finished to edit textBoxA, you should use the Leave event:
this.textBoxA.Leave += new System.EventHandler(this.textBoxA_Leave);
private void textBoxA_Leave(object sender, EventArgs e)
{
textBoxB.Text = textBoxA.Text;
}

This should do what you need:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text;
}

Even shorter (better?) than the event approach is using winform's databinding. Just use this right after the InitializeComponents call:
readonlyTextBox.DataBindings.Add("Text", writableTextBox, "Text");

Related

Grabbing the textbox label

Hello im making my first project with about 10 different textboxes where the user puts data in. when he/she clicks the the textbox the textbox text clears and a virtual numpad form pops up and when he leaves the textbox the numpad "hides".
right now (or i would) i have 2 events for every textbox, a click event and a leave event,
private void sheetWidthBox_Enter(object sender, EventArgs e)
{
vnumPadForm.Location = PointToScreen(new Point(sheetWidthBox.Right, sheetWidthBox.Top));
vnumPadForm.Show();
}
Im sure there is a way of dynamically coding that in one event and just grabbing the label name. i have played around with it a bit on my numpad like this and it works good;
private void button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
string num = b.Text;
SendKeys.SendWait(num);
}
Like that but instead i want to get the label name
right now (or i would) i have 2 events for every textbox, a click event and a leave event,
it works but very inefficient.
Change the name of the handler to something generic like "anyBox_Enter()", and update to the code below:
TextBox curTextBox = null;
private void anyBox_Enter(object sender, EventArgs e)
{
curTextBox = sender as TextBox;
vnumPadForm.Location = PointToScreen(new Point(curTextBox.Right, curTextBox.Top));
vnumPadForm.Show();
}
Note that I added a class level variable called "curTextBox" that gets set from the generic handler! This will track whatever TextBox was entered last.
Now, one by one, select each TextBox on your Form that you want to wire up to this common handler. After selecting each one, in the Properties Pane, click on the "Lightning Bolt" Icon to switch to the events for that control if they are not already showing. Find the "Enter" entry and change the dropdown to the right so that it says "anyBox_Enter".
Then in your button click handlers you can use the "curTextBox" variable to know where to send the key:
private void button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
string num = b.Text;
if (curTextBox != null) {
curTextBox.Text = num; // or possibly APPEND this to the TB?
}
}

Winform copy button text to textbox using universal method

So this is a fairly straightforward thing, and I am just curious if there is a better way to do it to save lines of code. For class we are making a teletype machine. Basically there is a textbox, and a series of buttons A-Z and 0-9. When you click the button it adds the corresponding letter/number to the textbox. When you click send, it adds the contents of the textbox to a label and resets the textbox. Everything works and it only took a few minutes to build. However there is a mess of redundant lines and I was curious if there is a way to clean up the code with a method.
This is my current code.
private void btn_A_Click(object sender, EventArgs e)
{
box_UserInput.Text = box_UserInput.Text + "A";
}
As you can see, it is very simplistic and straight forward. Click A, and "A" gets added to the textbox. However the Text property of the button is also just "A" and I want to know if there is a way to just copy the text property of that button and add it to the textbox string.
Something like this, except with a universal approach where instead of having to specify btn_A it just inherits which button to copy based on the button clicked. That way I can use the same line of code on every button.
private void btn_A_Click(object sender, EventArgs e)
{
box_UserInput.Text = box_UserInput.Text + btn_A.Text;
}
You can use this which is more universal as the Control class contains the Text property. Also, using the best practice $"".
private void btn_A_Click(object sender, EventArgs e)
{
box_UserInput.Text = $"{box_UserInput.Text}{((Control)sender).Text}";
}
You can also assign the same event to each button. Create an event, say addControlTextOnClick and assign the same event to each button.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addControlTextOnClick(object sender, EventArgs e)
{
box_UserInput.Text = $"{box_UserInput.Text}{((Control)sender).Text}";
}
}
You can even shorten this more using this C# construct:
private void addControlTextOnClick(object sender, EventArgs e) =>
box_UserInput.Text = $"{box_UserInput.Text}{((Control)sender).Text}";

Multiple OnClick events in c#

I want to ask if i have multiple labels with same function Onclick but with different parameters. How i can handle them without make 30 methods.
I want to make A-Z Filter in windows forms application with C#. I have label for each character (A,B,C,D....,Z). Also i have TreeView with data from DB.
private void labelLetter1_Click(object sender, EventArgs e)
{
//this.labelLetter1.Text
// get value of the label and refresh treeview
}
I want to make this on every characters but without repeat same code.
subscribe an example event to other ones. try like this:
private void labelLetter1_Click(object sender, EventArgs e)
{
Label lbl = (Label) sender;
var text = lbl.Text;
//this.labelLetter1.Text
// get value of the label and refresh treeview
}
now set this event to other labels from Properties window.
The sender parameter is going to be the original object that triggered the event. In your case, it is going to be a Label. This means you could cast the object to a Label.
Additionally you could make a single label_click method and have all labels user that single method.
For example:
private void label_Click(object sender, EventArgs e)
{
String labelText = (sender as Label).Text;
//Your process
}

FireTextChanged event of TextBox B when TextChanged event of TextBox A occurs

I have two TextBoxes: A and B.
I want B to imitate the behavior of A. So whenever A's text changes, B's text changes too.
This is doable by setting B's text to A's text whenever A's text changes. But since B has an AutoComplete option, this AutoComplete will not work unless B's TextChange event is fired, too.
So with each TextChange in A, I want to fire a TextChange in B.
How can I achieve this?
void TextChanged_A(object sender, EventArgs e)
{
//Do Anything
//Then
TextChanged_B(B,null);
}
void TextChanged_B(object sender, EventArgs e)
{
//Do Anything
}
An easy way to do is the TextChanged Event Of TextBox 1.
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text;
}

Auto refresh labels as text boxes text input data into method

Here is my method that I' am trying to have automatically refresh my label. When I have my label as a click event...the answer refreshes and is correct.
private void Calculate()
{
dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
double UtilRounded1 = Math.Round(dblUtil1 * 100);
strUtil1 = UtilRounded1.ToString() + "%";
}
Here is the Validated label event that does not update when text is changed in my text boxes.
private void lblUtil1_Validated(object sender, EventArgs e)
{
Calculate();
}
If this is correct...what am I missing? is there something I need to do on the text boxes that will trigger validation?
I have also tried a text changed event that yields the error cannot implicitly convert type void(or any type for that matter) to EventHandler. Here is the code.
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
lblUtil1.TextChanged += Calculate();
}
Any help is appreciated! I've been banging my head on my keyboard for a day now.
First at all, you have to handle events for the TextBox that you input value to calculate, such as when you change vale in the TextBox or validate it.
So if you have textBox1 then you should have this handling (trigger when value in textBox1 is changed)
private void textBox1_TextChanged(object sender, EventArgs e)
{
lblUtil1.Text = Calculate();
}
I assume that you want to display value in strUtil1 at the label lblUtil1, so you have to change your Calculate method like this
private string Calculate()
{
dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
double UtilRounded1 = Math.Round(dblUtil1 * 100);
strUtil1 = UtilRounded1.ToString() + "%";
return strUtil1;
}
EDITED
This is a sample code for validate the required TextBoxes.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == "")
{
e.Cancel = true;
lblUtil1.Text = "textBox1 is required!";
}
}
Try calling yourlabelname.Refresh() i.e like
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
lblUtil1.TextChanged = Calculate();
lblUtil1.Refresh();
}
or
private void lblUtil1_TextChanged(object sender, EventArgs e)
{
Calculate();
lblUtil1.Refresh();
}
You need to do a couple things.
First, stop using "hungarian" notation. It's bad. It's bad for a lot of reasons. MS even says, "don't use hungarian" as most people get it wrong as your code shows. Instead, name your variables appropriately. For example, dblSG has absolutely zero meaning.
Second, please reread Michael's answer to your question from yesterday ( https://stackoverflow.com/a/20026642/2424 ). He did NOT say to use lblUtil1_Validated. He said to use TextBox_Validated. In other words, the event you should have your calculation run on is with the textbox fields on your form. He also suggested you just use the textboxes TextChanged events in order to cause the calculation to run as they are typing. Personally, I don't agree with that but whatever.
A third possible option is to simply go back to your original solution. Meaning, just run the calculation when the label is clicked. In which case you should refer back to your original question as Michael failed to answer it.

Categories