2014-12-30 32 views
2

我想编写一个简单的“注册/登录”程序,仅供我玩,只是为了好玩。C#通过长度更改txtBox BackColor

我想更改用户键入其名称的TxtBox的颜色。当txtBox.Length<4它应该将其背景更改为红色。

我不知道为什么我的代码不起作用。当我将txtBox属性中的文本牢固地更改为5以上时,它在开始时是蓝色的,但之后不会改变。

我的代码:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace _4Fun 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      if (regTxtBoxName.TextLength<4) { 
       regTxtBoxName.BackColor = Color.Red; 
      } 
      else{ 
       regTxtBoxName.BackColor = Color.DarkBlue; 
      } 
     } 
    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    private void regBtn_Click(object sender, EventArgs e) 
    { 
     if (regTxtBoxName.TextLength < 4) 
     { 
      txtBoxStatus.Text = "Choose a name with minimal length 5. "; // Urobit txtboxname a pass v registru červene pozadie ak x<4 
     } 
     else { 
      txtBoxStatus.Text = "Your account has been successfully created."; 
      string name = regTxtBoxName.Text; 

     } 
     if (regTxtBoxPass.TextLength < 4) 
     { 
      txtBoxStatus.Text = txtBoxStatus.Text + "Choose password with minimal length 5. "; 
     } 
     else { 
      txtBoxStatus.Text = "Your account has been successfully created."; 
      string pass = regTxtBoxPass.Text; 
     } 

    } 
} 
} 

回答

3

您的代码设置颜色形式的构造函数,然后你不改变它。您需要在TextBox上注册TextChanged事件,以在您的应用运行时根据您的Textbox中有多少个字符来更改颜色。

2

处理你的文本框中TextChanged事件,并将此码在那里,在构造函数中没有

if (regTxtBoxName.TextLength<4) { 
    regTxtBoxName.BackColor = Color.Red; 
} 
else{ 
    regTxtBoxName.BackColor = Color.DarkBlue; 
} 
0

您可能希望将regBtn_Click方法更改为regBtnTextChanged。通过这样做,那么文本框的颜色将在运行时改变。

因此,代码是:

private void regBtnTextChanged(object sender, EventArgs e) 
    { 
     if (regTxtBoxName.TextLength<4) { 
      regTxtBoxName.BackColor = Color.Red; 
     } 
     else{ 
      regTxtBoxName.BackColor = Color.DarkBlue; 
     } 
    } 
1

您可以TextboxTextChanged事件做到这一点。 这里是代码

void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    if (textBox1.TextLength<4) 
    { 
     textBox1.BackColor = Color.Red; 
    } 
    else 
    { 
    textBox1.BackColor = Color.DarkBlue; 
    } 
} 

当你在输入文本框中的文本TextChanged事件将调用。检查链接http://www.dotnetperls.com/textchanged