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(" ");
}
}
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.
Assuming you want to display :
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);
}
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 ", "");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.