C#登录表单,登录按钮没有响应
问题描述:
所以,我是VS和C#的新手,我自学的时候更好地理解了我使用的产品的后端。我创建了一个包含一些信息和登录表单的小型数据库。一切似乎都可以正确编译,但登录按钮在点击时不响应,取消按钮也不会。不知道我缺少什么,代码如下:C#登录表单,登录按钮没有响应
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;
using System.Data.SqlClient;
namespace CorpLogin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//DB Connection String
string cs = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CORPORATION.mdf;" +
"Integrated Security=True";
//Login Button clicked
private void LoginButton1_Click(object sender, EventArgs e)
{
//Validates text entered
if (userNameText1.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD are required fields.");
return;
}
if (passwordText1.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD are required fields.");
return;
}
try
{
//Connect to SQL
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("select * from USERS where [email protected]" +
"and [email protected]", con);
cmd.Parameters.AddWithValue("@username", userNameText1.Text);
cmd.Parameters.AddWithValue("@password", passwordText1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
//Show new form or fail message
if (count == 1)
{
this.Hide();
CorpView cv = new CorpView();
cv.Show();
}
else
{
MessageBox.Show("ACCESS DENIED");
}
}
//Catch program exceptions
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Cancel Button Clicked
private void CancelButton1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
任何帮助表示赞赏。谢谢。
答
您还必须添加事件处理程序注册。
这可以在设计人员来完成表单中的手动双击该按钮,或:
LoginButton1.Click += new System.EventHandler(LoginButton1_Click);
答
所以我的问题的原因是如上所述。我没有将事件处理程序映射到按钮。从设计师,我查找属性,并选择事件方法(闪电图标),在点击我设置登录按钮LoginButton1_Click和取消按钮我将其设置为CancelButton1_Click。
我遇到了数据库连接的错误,但我知道如何解决这个问题。取消按钮按预期关闭程序。
你使用Winforms吗?另外,哪个版本的VS? – Hank
你偶然重命名你的按钮?事件处理程序看起来没问题。 – Fang
转到窗体设计器单击按钮,然后查看这个'LoginButton1_Click'的事件单击按钮的下拉列表单击偶数并选择该方法..否则,双击Button Click事件并让IDE自动创建它为你 – MethodMan