在另一个文本框中显示中的字符


private void button1_Click(object sender, EventArgs e)
{
string c;
string a;
int b = 0;
foreach (char m in textBox1.Text)
{
b++;
a = m.ToString();
if (a=="a"&&b==1)
{
textBox2.Text = "Error";
}
c = m.ToString();
textBox2.Text = c;

}
}

你好我想在文本框1中键入一些内容,并在文本框2中查看文本框1的字符例如:在文本框1中键入"Hello",然后在文本框2中看到"H e l l o",但我在文本框2 中看到了文本框1"o"的最后一个字符

我该怎么办?

您可以使用string.Join()并一次性完成:

private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(textBox1.Text)) return;
if(textBox1.Text[0] == 'a')
{
textBox2.Text = "Error";
return;
}
textBox2.Text = string.Join(" ", textBox1.Text.ToCharArray());
}
textBox2.Text = c;

这将覆盖textBox2。尝试

textBox2.Text += c;

编辑:作为一名学生,我要简化。

对于空格,将上一行替换为:

if(b==1)//that means this is first char of your textbox. And we wont add spaces.
{
textBox2.Text+=c;
}
else//that means its not first, and we need to add spaces.
{
textBox2.Text+= ' '+c;
}

但有一些事情你需要注意:

  • c是多余的,正如我在评论中所说。尝试将所有c的替换为a的,包括解决方案
  • 这个答案更简单,但@BoredomOverload的答案更好。考虑使用它

您可以使用TextChanged事件处理自动完成:

textBox1.TextChanged += TextBox1_TextChanged; //set up this first
void TextBox1_TextChanged(object sender, EventArgs e)
{
var text1WithSpaces = string.Join(" ", textBox1.Text.ToCharArray());
textBox2.Text = text1WithSpaces;
}

最新更新