I am currently working with appending text to textboxes. In a winform I have two checkboxes and one textbox. Every time a check box is checked a text appears inside the textbox. But I am having difficulties taking out the text when the checkbox is unchecked. How can append text when checkbox is checked and take out text when unchecked?
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
ck = sender as CheckBox;
if (ck != null && ck.Checked)
{
textBox1.AppendText(" Example1 ");
}
else
{
textBox1.AppendText(" ");
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
ck = sender as CheckBox;
if (ck != null && ck.Checked)
{
textBox1.AppendText(" Example2 ");
}
else
{
textBox1.AppendText(" ");
}
}
Assuming you want to display :
Example 1 when the first checkbox is checked
Example 2 when the second is checked
Example 1 and Example 2 if both are checked
Empty if both are unchecked
The best is to centralize the UI logic in a single method that reflect your rules:
The approach is different as removing text I dont need. I start from an empty list and I fill it regarding the checkboxes are checked or not. Then I display it. By this way, I dont have to cope with trailing separators.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
UpdateTextBox();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
UpdateTextBox();
}
void UpdateTextBox()
{
var words = new List<string>();
if (checkbox1.Checked)
words.Add("Example 1");
if (checkbox2.Checked)
words.Add("Example 2");
textBox1.Text = string.Join(" ", words);
}
To take out just the text you added, you can use String.Replace:
textBox1.Text = textBox1.Text.Replace(" Example1 ", "");
Note that if the user changes the value, this text may or may not still be in the TextBox. I assume you are aware of this or this is simply an exercise.
if (ck != null && ck.Checked)
textBox1.Text = "Example";
else
textBox1.Text = "";
Do you mean
textBox1.Text = string.Empty
Or am I missing something ?
Try this
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
ck = sender as CheckBox;
if (ck != null && ck.Checked)
{
textBox1.AppendText(" Example1 ");
}
else
{
textBox1.Text = textBox1.Text.Replace(" Example1 ", "");
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
ck = sender as CheckBox;
if (ck != null && ck.Checked)
{
textBox1.AppendText(" Example2 ");
}
else
{
textBox1.Text = textBox1.Text.Replace(" Example2 ", "");
}
}
Related
I have a ListBox that when an item is selected, it is shown in a label as well. However, when I want to remove the selected item, program breaks and shows a NullReferenceException.
My code:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = "Your Selected: " + listBox1.SelectedItem.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = "";
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
It may appear, that there's no selected item in the listbox, so you have to check for that:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = null == listBox1.SelectedItem
? ""
: "Your Selected: " + listBox1.SelectedItem.ToString();
}
private void button2_Click(object sender, EventArgs e) {
// Looks redundant, listBox1_SelectedIndexChanged will do
//label1.Text = "";
// Deselect item, but not remove it
if (listBox1.SelectedIndex >= 0)
listBox1.SelectedIndex = -1;
// In case you want to remove the item (not deselect) - comment out the code below
// if (listBox1.SelectedIndex >= 0)
// listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
Edit: as for counting listbox items, there's no event fo this in the current listbox implementation. So you have to do it manually:
if (listBox1.SelectedIndex >= 0) {
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
lbItemsCount.Text = listBox1.Items.Count.ToString();
}
Another way is to use click event of the list box , if we do not want to double click the one list box item for the deselection of another list items.
ex:
private void ListBox_Right_Click(strong textobject sender, EventArgs e)
{
Btn_Left.Enabled = ListBox_Right.SelectedIndex >= 0;
ListBox_Left.ClearSelected(); // to clear the list selection/highlight
Btn_Right.Enabled = false; // for my specification
}
}
private void ListBox_Left_Click(object sender, EventArgs e)
{
Btn_Right.Enabled = ListBox_Left.SelectedIndex >= 0;
ListBox_Right.ClearSelected(); //to clear the list selection/highlight
Btn_Left.Enabled = false;// for my specification
}
I got few textboxes in my form. I would like to type in one textbox and the other textboxes will be automatically canceled (Canceled so the user wont be able to type anymore in the other textboxes).
If the user delete the word he typed in the textbox (or in other words: if the textbox is empty) all other textboxes will be enabled again.
Here is what I got so far:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
// Disable other textboxes (I have no idea how can I do that).
}
else if (textBox1.Text.Trim().Length == 0)
{
// Enable other textboxes
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
// Keep this comboBox enabled while typing in textBox1.
}
}
How can I disable other textboxes while typing in priticillar textbox? (also keeping comboBox enabled).
DO NOTICE: I would like to do the same on textBox2 (when I type in textBox2, textbox 1 and 3 will be disabled) and textBox3.
You don't need a condition on your 'else if', just 'else' will do, as if the length is more than 0, the only other possibility is 0. Also you can use the sender instead of hardcoding the control name.
Then set the Enabled property for the textbox's you want disabled. You can loop through all the textbox's on the form, excluding the one you are typing into, or just manually list them. SImpler is putting the textbox's in a groupbox, then if you disable the groupbox it will disable the controls with in it.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var senderTextBox = (TextBox)sender;
var textBoxesEnabled = senderTextBox.Text.Trim().Length == 0;
textBox2.Enabled = textBoxesEnabled;
textBox3.Enabled = textBoxesEnabled;
// OR
groupBox1.Enabled = textBoxesEnabled;
}
REPLY EDIT: You can chain of textbox's, say 4 of them, disable the last 3, then:
void TextBox1TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox2.Enabled = !isTextEmpty;
}
void TextBox2TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox1.Enabled = isTextEmpty;
textBox3.Enabled = !isTextEmpty;
}
void TextBox3TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox2.Enabled = isTextEmpty;
textBox4.Enabled = !isTextEmpty;
}
void TextBox4TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox3.Enabled = isTextEmpty;
}
But for a large amount of textbox's, another alternative is having multiple textbox share the same TextChanged event. You need to click on each TextBox control, go into the Events list and manually select the method for TextChanged. Here is the method:
private void TextBoxGroup_TextChanged(object sender, EventArgs e)
{
var groupOrder = new List<TextBox>() { textBox1, textBox2, textBox3, textBox4 };
var senderTextBox = (TextBox)sender;
var senderIndex = groupOrder.IndexOf(senderTextBox);
var isTextEmpty = senderTextBox.Text.Trim() == "";
if (senderIndex != 0) groupOrder[senderIndex - 1].Enabled = isTextEmpty;
if (senderIndex != groupOrder.Count - 1) groupOrder[senderIndex + 1].Enabled = !isTextEmpty;
}
Use Controls collection and some LINQ:
if (textBox1.Text.Trim().Length > 0)
{
var textboxes = this.Controls.OfType<TextBox>().Where(x => x.Name != "textBox1");
foreach(var tBox in textboxes)
tBox.Enabled = false;
}
If I have two text boxes on a form, how can I make it so that their text properties are perfectly synced? Similar to what would happen if they both processed the same KeyDown event.
I would do it this way:
textBox1.TextChanged += (s, _) =>
{
if (!textBox2.Focused && textBox1.Text != textBox2.Text)
{
textBox2.Text = textBox1.Text;
}
};
textBox2.TextChanged += (s, _) =>
{
if (!textBox1.Focused && textBox2.Text != textBox1.Text)
{
textBox1.Text = textBox2.Text;
}
};
Basically I'm responding to the TextChanged even on each text box, but making sure that the target text box doesn't have focus and that the text actually has changed. This prevents infinite back-and-forth loop trying to update the text and it makes sure that the current insertion point isn't changed by the text being overwritten.
I would say that you partially answered your own question, have them both assigned to the same TextChanged EventHandler check which textbox has changed then update the Text property of the other one, something like this.
private void textBox_TextChanged(object sender, EventArgs e)
{
if (((TextBox)sender).Equals(textBox1))
textBox2.Text = ((TextBox)sender).Text;
else
textBox1.Text = ((TextBox)sender).Text;
}
Modified Code to Keep Carat Position Synced between the two TextBox's , see if this is what you are wanting.
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Equals(textBox1))
{
if (textBox2.Text != tb.Text)
{
textBox2.Text = tb.Text;
textBox2.SelectionStart = tb.SelectionStart;
textBox2.Focus();
}
}
else
{
if (textBox1.Text != tb.Text)
{
textBox1.Text = tb.Text;
textBox1.SelectionStart = tb.SelectionStart;
textBox1.Focus();
}
}
}
I would simply do as follows:
bool flag1, flag2;
private void t1_TextChanged(object sender, EventArgs e)
{
if (flag2) return;
flag1 = true;
t2.Text = t1.Text;
flag1 = false;
}
private void t2_TextChanged(object sender, EventArgs e)
{
if (flag1) return;
flag2 = true;
t1.Text = t2.Text;
flag2 = false;
}
I'm making a textbox to input some Product's Price, and I don't want the user to input "." more than once. "." can not be the first character (which I know how to do). But I need to make the textbox accept this character "." not more than once. How ? And no, I don't want to use MaskedTextBox.
Put it in KeyPress event in your textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string inputChar = e.KeyChar.ToString();
if (inputChar == ".")
{
if (textBox1.Text.Trim().Length == 0)
{
e.Handled = true;
return;
}
if (textBox1.Text.Contains("."))
{
e.Handled = true;
}
}
}
Try this
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.IndexOf('.') != textBox1.Text.LastIndexOf('.'))
{
MessageBox.Show("More than once, not allowed");
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
}
}
I have some Company names as Items in a ComboBox like this:
123 SomeCompany
Always a number between 100 and 999 plus the company name.
Now if the user selects an Item I want the TextBox to only show the number, not the company name. he company name should only be visible when he drops down the ComboBox...
I tried to set ComboBox1.Text = ComboBox.Text.Substring(0, 3) in the SelectedIndexChanged-Event and the TextChanged-Event, but it didn't do anything, there was always everything in the ComboBox...
AutocompleteMode is set to none.
What did I do wrong?
To always format the value, you could use the Format event (with FormattingEnabled = true)
private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = e.Value.ToString().Substring(0, 3);
}
But if you want the full value to be displayed when the dropdown is shown, you can temporarily disable the formatting:
private void comboBox1_DropDown(object sender, EventArgs e)
{
comboBox1.FormattingEnabled = false;
}
private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
comboBox1.FormattingEnabled = true;
}
Try this
textbox1.Text = ComboBox1.SelectedItem.ToString().SubString(0, 3);
Try something like this:
private void combox1_ SelectedIndexChanged(object sender,EventArgs e)
{
string value = (combox1.selectedItem != null) ?
combox1.selectedItem.ToString().Substring(0, 3) : string.Empty;
}