I have a KeyPress event bound on multiple TextBoxs and I want to check which TextBox is getting clicked and do different things depending on the one clicked.
I'm trying to compare which TextBox is getting clicked based on the .Name attribute of the text box. I'm doing this in a switch statement, but am getting a Constant value is expected.
private void UpdateValues(object sender, KeyPressEventArgs e)
{
TextBox textBox = (TextBox)sender;
switch (textBox.Name)
{
case txtBox1.Name: // Error here
break;
}
}
Is there a way to get around this? I don't want to hard code the .Name as a string in case future developers work on this.
Can I do this, or will it become a run time error?
private const string _TXTBOX1NAME = txtBox1.Name;
private void UpdateValues(object sender, KeyPressEventArgs e)
{
TextBox textBox = (TextBox)sender;
switch (textBox.Name)
{
case _TXTBOX1NAME: // Use the const variable
break;
}
}
EDIT:
Actually, you cannot assign const values like that.
How would I compare which TextBox has a KeyPress without hard coding the .Name as a string in the case statement?
You can't use the switch like that. The cases need to be compile-time constants.
You could do:
private void UpdateValues(object sender, KeyPressEventArgs e)
{
TextBox textBox = (TextBox)sender;
switch (textBox.Name)
{
case "NameTextBox":
break;
case "PasswordTextBox":
break;
}
}
If you know the names, this would be possible. Your example fails, because textbox1.Name is not a constant, but a property read from the instance of one TextBox.
Another way would be to use the textbox reference, given as the sender:
private void UpdateValues(object sender, KeyPressEventArgs e)
{
TextBox textBox = (TextBox)sender;
if(textBox == textBox1) { ... }
if(textBox == textBox2) { ... }
}
But IMHO the best solution would be to use two change-callbacks, one for each method. Then you do not need to compare the textboxes or the textbox's names.
So you could change UpdateValues into one UpdateUserName and UpdatedPasswort. Doing this, the method name will clearly show, what the method does(, or at least should do), making your code a lot more readable.
try this
private void UpdateValues(object sender, KeyPressEventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Name == textBox1.Name){
//error
} else if(textBox.Name == textBox2.Name){
// and so on
}
}
Related
I used System.Globalization.CultureInfo.InvariantCulture on my Textbox, but whenever I enter the Textbox and leave without altering the value it adds two more zeros, how can I sort this out?
private void textBox1_Leave_1(object sender, EventArgs e) {
double txt = double.Parse(textBox1.Text,
System.Globalization.CultureInfo.InvariantCulture);
textBox1.Text = txt.ToString("N2");
return;
}
Well, in general case, you can keep a collection of Coltrols which were manually edited and on control leaving check if the control is in the collection. Assuming that you work with WinForms:
using System.Globalization;
...
private readonly HashSet<Control> m_EditedControls = new HashSet<Control>();
// On each textBox1 change we should decide if we are going
// to update control's Text on leave or not
private void textBox1_TextChanged(object sender, EventArgs e) {
// If TextBox1 was edited while having keyboard focus,
// i.e. user got focus and edit the textbox manually
// put textbox as edited
if (sender is TextBox box && box.Focused)
m_EditedControls.Add(box);
}
Then on leaving textBox1 you can check if textBox1 has been edited manually:
// On leaving textBox1 we and an additional check
// if textBox1 has been edited manually
private void textBox1_Leave(object sender, EventArgs e) {
if (sender is TextBox box &&
m_EditedControls.Contains(box) &&
double.TryParse(box.Text, CultureInfo.InvariantCulture, out var value)) {
box.Text = value.ToString("N2", CultureInfo.InvariantCulture);
m_EditedControls.Remove(box);
}
}
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.
I'm in a situation and I want to know that it is possible or not.
I want to change the Items of ListBox control depend on TextBox value.
Means when I change textbox value, the listitems of ListBox changes asynchronously (without pressing button or something).
Is it possible? If it is possible please guide me some references, tutorials or something.
Not completely getting what you need,but i hope the cases below would help you;
Case 1 : If you have a listbox with several items in it and you want the item to be selected that matches the text in textbox. If this is the case the code below should do the job;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.TextLength >= 1)
{
int index = listBox1.FindString(textBox1.Text);//Search any items that match Textbox's text.
listBox1.SelectedIndex = index;//Highlight the match
}
else
{
listBox1.SelectedIndex = 0;
}
}
Add the code above to the TextChangedEvent of your textbox and make sure you rename the controls in the code with the ones you have.If this is not the case,see the below one;
Case 2 : You have a textbox and you want to add the text of textbox to listbox.On more thing i would like to tell you,the code below assumes that when you press the Enter Key while the textbox is focused,it's text(if any) should be added to listbox.Add the code below in KeyDownEvent of your textbox,and make sure to rename the controls.If this is the case the code below would help you;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string item = textBox1.Text;
if (textBox1.Text.Length >= 1)
{
if (e.KeyCode == Keys.Enter)//If Enter key is pressed while textbox is focused.
{
listBox1.Items.Add(item);
}
}
}
Hope this helps you.
I hope the below code will help you:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if(TextBox1.Text == "One")
listBox1.Items.Add("One");
if(TextBox1.Text == "two")
listBox1.Items.Add("two");
}
You don't have to do that async. Just use the TextBox.TextChanged-Event.
how to do validations for numeric,double and empty values for datagridview in c# windows application.Text values should not be allowed to enter the cells which are numeric or double.how to do it?
You Can validate datagrid view cell like this...
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (e.FormattedValue == null && String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
}
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Clear the row error in case the user presses ESC.
dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
}
This validates only empty values , if you want validate numericals you can do like this...
I hope it will helps you...
If you'd like to restrict anything but numbers from being entered, you need to handle the EditingControlShowing event on the DataGridView. It can be done like this:
dataGridView.EditingControlShowing = new DataGridViewEditingControlShowingEventHandler (dataGridView_EditingControlShowing);
Then, define your handler:
void dataGridView_EditingControlShowing (object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox tx = e.Control as TextBox;
tx.KeyPress += new KeyPressEventHandler (tx_KeyPress_int);
}
Then, define your KeyPress handler, and only handle numeric characters:
void tx_KeyPress_int (object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber (e.KeyChar) || e.KeyChar == '\b'))
{
//is NOT number or is Backspace key
e.Handled = true;
}
}
Adjust to suit your exact needs accordingly (i.e. handle only input on a certain column, etc.)
If you want to validate cell values when user trying to leave cell, you should handle DataGridView.CellValidating event and process cell value there.
If you want to validate value when user typing it, you may handle KeyPress event.
To validate numeric values you may use code like this:
int number = 0;
if(!int.TryParce(cell.Value.ToString(), out number))
{
//report about error input
}
Please read this link.
http://msdn.microsoft.com/en-us/library/aa730881(v=vs.80).aspx
##Edit ,
if you try to use your own custom numeric control,
1. you no need to check any additional validation.
2. It is reusable.
I have two textboxes, and a button. When I press the button, I want to know where my current caret is (either of the two boxes). I need this to know where to insert a certain text. I tried textbox1.Focused; textbox1.enabled but neither worked. How should I implement this? Thanks
Keep in mind that when you click the button, your textboxes will no longer have focus. You'll want a method of keeping track of what was in focus before the button's click event.
Try something like this
public partial class Form1 : Form
{
private TextBox focusedTextbox = null;
public Form1()
{
InitializeComponent();
foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
tb.Enter += textBox_Enter;
}
}
void textBox_Enter(object sender, EventArgs e)
{
focusedTextbox = (TextBox)sender;
}
private void button1_Click(object sender, EventArgs e)
{
if (focusedTextbox != null)
{
// put something in textbox
focusedTextbox.Text = DateTime.Now.ToString();
}
}
}
There's a very simple way to do this.
Your requirement is simple since you only have two textboxes.
You can assign a class-wide string variable that holds when textbox1_GotFocus() is invoked as well as textbox2_GotFocus().
So if that textbox GotFocus() is called you assign a value.
Then put a condition for the class-wide string variable in the button that if the class-wide variable has a value of thats kind, that textbox is populated whatever you want to put in the textbox.
It worked for me so I believe it should work on you.