Let's say i have a textbox and a button, how can i make that button convert the no result (or nothing entered in textbox) to result 0?
private void button1_Click(object sender, EventArgs e)
{
if (this.dateTimePicker1.Text != "")
{
listBox1.Items.Add(this.dateTimePicker1.Text);
}
textBox2.Text += " Woman";
if (this.textBox2.Text != "")
{
listBox1.Items.Add(this.textBox2.Text);
}
textBox3.Text += " People";
if (this.textBox3.Text != "")
{
listBox1.Items.Add(this.textBox3.Text);
}
}
If there's nothing entered in textBox2 or textBox3 it converts the result to " Woman" or " People", but i want it to be "0 Woman" & "0 People" - IF NOTHING is entered in textbox. Can anyone help me out?
This is the thing I would do with DRY (Don't repeat yourself)
// Make a list of textboxes and string
List<Tuple<TextBox, String>> textBoxesTest = new List<Tuple<TextBox, String>>();
// Add the information
textBoxesTest.Add(new Tuple<TextBox, String>(textBox2, "Woman"));
textBoxesTest.Add(new Tuple<TextBox, String>(textBox3, "People"));
// Go through the list
foreach(var tuple in textBoxesTest) {
// tuple.Item1 is a TextBox
// tuple.Item2 is a String
if(String.IsNullOrEmpty(tuple.Item1.Text)) {
tuple.Item1.Text = String.Format("0 {0}", tuple.Item2);
} // if end
else { /* do some other with it */ }
} // foreach end
Don't test string for emptyness with str == ""
. Use the String.IsNullOrEmpty(str)
method to check this condition. It is faster, because str == ""
will create a new String reference to "". Is null or Empty has the condition value == null || value.Length == 0;
value == null || value.Length == 0;
which will not create instances of a string.
Also make no use of String concatenations, because each will be written in the RAM and then needs to concatenate each time it is used. Better make the use of the String.Format(str, args[])
method.
The above code is well in the issue of maintainability. You just need to add a tuple to the list when adding another textbox "doing the same", and not add if/else algorithm by copy/paste the code. This would be an common error source.
Add following just before last line of function, in order to make nothing into textBox
textBox2.Text = "";
textBox3.Text = "";
Add an if-else to check if the textbox text is null and then change the text outrightly rather than appending text to the existing text. Like this
if (textBox2.Text == "" && textBox3.Text == "")
{
textBox2.Text = "0";
textBox3.Text = "0";
}
You are very close! Test the contents of textBox2 and textBox3, before appending extra text to it:
if (textBox2.Text == "")
{
textBox2.Text = "0";
}
textBox2.Text += " Woman";
There are two possibilities to this situation.
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.