“你可以教我如何禁用按钮,直到所有文本框都不为空。” 在我的设计表单中命名登录。 我有2个文本框和2个按钮 我想禁用按钮,直到所有文本框都不为空
帮助我 所以我在c#windows应用程序表单中的代码
SqlConnection con = new SqlConnection(@"Data Source=ADMIN-\MSSQLSERVERR;Initial Catalog=Admin;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Select USN From Admin where USN ='" + textBox1.Text + "'and Password ='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Admin_Panel aa = new Admin_Panel(dt.Rows[0][0].ToString());
aa.Show();
}
else
{
MessageBox.Show("Please check your username and password");
textBox1.SelectAll();
textBox2.Text = "";
}
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Select USN From Admin where USN ='" + textBox1.Text + "'and Password ='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Student aa = new Student(dt.Rows[0][0].ToString());
aa.Show();
}
else
{
MessageBox.Show("Please check your username and password");
textBox1.SelectAll();
textBox2.Text = "";
}
button2.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
e.Handled = true;
base.OnKeyPress(e);
}
我尝试了我所知道的一切,但它不起作用:( 我也试试这个button1.Enabled =!string.IsNullOrWhiteSpace(textBox1.Text); 但是当我已经将USN和密码放在文本框中时,2个按钮未启用
答案 0 :(得分:3)
首先将您的buttons.Enabled属性设置为false。然后为两个TextBox添加TextChanged-Handler,在其中检查两个TextBox是否包含某些内容。
处理程序的代码可能如下所示:
private void textBox1_TextChanged(object sender, EventArgs e)
{
setButtonVisibility();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
setButtonVisibility();
}
private void setButtonVisibility()
{
if ((textBox1.Text != String.Empty) && (textBox2.Text != String.Empty))
{
button1.Enabled = true;
button2.Enabled = true;
}
else
{
button1.Enabled = false;
button2.Enabled = false;
}
}
答案 1 :(得分:1)
您需要在其Changed事件中监控文本框的更改,例如:
private void textbox1_Change(object sender, EventArgs e)
{
ConditionallyEnableSubmitButton();
}
private void textbox2_Change(object sender, EventArgs e)
{
ConditionallyEnableSubmitButton();
}
private void ConditionallyEnableSubmitButton()
{
button1.Enabled = (!string.IsNullOrWhiteSpace(textBox1.Text) ||
!string.IsNullOrWhiteSpace(textBox2.Text));
}
提示不收取任何额外费用:提供任何控件,您将以编程方式引用一个可识别的名称,例如“btnSubmit”,“txtbxUsername”,“txtbxPwd”等。
你可以做的比阅读史蒂夫麦康奈尔的“代码完整”更糟糕,因为这和其他许多方面的良好实践。
答案 2 :(得分:0)
private void textbox1_TextChanged(object sender, EventArgs e)
{
EnableButton();
}
private void textbox2_TextChanged(object sender, EventArgs e)
{
EnableButton();
}
private void EnableButton()
{
if(textbox1.Text == "" || textbox2.Text == "")
{
button1.Enabled = false;
button2.Enabled = false;
}
else
{
button1.Enabled = true;
button2.Enabled = true;
}
}