I have 5 checkboxes and 5 Textboxes. I an trying to Replace characters in a string by checking checkboxes. for example if I checked checkbox 2 and 3 then only 2 and 3 textboxes characters should be replace. if I check checkbox 1 then only 1 textbox characters should replace in string. it pick only one checkbox value only.
If CheckBox1.Checked Then
Dim x As String = Label9.Text
Dim y As String = x.Replace(x.Substring(1, 2), ComboBox2.Text)
Label8.Text = y
End If
If CheckBox2.Checked Then
Dim x As String = Label9.Text
Dim y As String = x.Replace(x.Substring(15, 2), word)
Label8.Text = y
End If
If CheckBox5.Checked Then
Dim x As String = Label9.Text
Dim y As String = x.Replace(x.Substring(13, 2), ComboBox5.Text)
Label8.Text = y
End If
If CheckBox8.Checked Then
Dim x As String = Label9.Text
Dim y As String = x.Replace(x.Substring(2, 1), ComboBox6.Text.Substring(1, 1))
Label8.Text = y
End If
CodePudding user response:
Try the following:
Dim y as String
Dim x As String = Label9.Text
If CheckBox1.Checked Then
y = x.Replace(x.Substring(1, 2), ComboBox2.Text)
End If
If CheckBox2.Checked Then
y = x.Replace(x.Substring(15, 2), word)
End If
If CheckBox5.Checked Then
y = x.Replace(x.Substring(13, 2), ComboBox5.Text)
End If
If CheckBox8.Checked Then
y = x.Replace(x.Substring(2, 1), ComboBox6.Text.Substring(1, 1))
End If
Label8.Text = y
CodePudding user response:
It is not a good idea to store the texts in labels. You need a data model that makes your logic independent of your controls. The controls are used for input and output, i.e., for the interaction with the user. The data model on the other side reflects the structure of the problem.
Example:
string[] sentence = { "I", "have", "nothing", "12" };
string[] replacement = { "You", "had", "something", "8" };
Based on this, you can initialize your controls. Assuming that the combo boxes are named ComboBox0 through ComboBox3 (rename them if not).
Label9.Text = String,Join(" ", sentence);
for (int i = 0; i < replacements.Length; i ) {
Controls["ComboBox" i].Text = replacements[i];
}
Then apply your logic
string[] result = new string[sentence.Length];
for (int i = 0; i < sentence.Length; i ) {
bool isChecked = ((ComboBox)Controls["ComboBox" i]).Checked;
if (isChecked) {
result = replacement[i];
} else {
result = sentence[i];
}
}
Finally, output the result:
Label8.Text = String,Join(" ", result);
You can also use String.Split
to create the word arrays:
string[] sentence = "I have nothing 12".Split(' ');
string[] replacement = "You had something 8".Split(' ');