我用c#构建Windows Form应用程序。该应用程序运行良好。 我已经添加了登录表单,但是当我单击登录按钮时,它停止在按钮单击侦听器内部。 这是我的代码:
private void add_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(Program.cs);
sqlCon.Open();
DataTable dtbl = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("dbo.login", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("@user", user.Text);
da.SelectCommand.Parameters.AddWithValue("@pass", pass.Text);
da.Fill(dtbl);
if (dtbl.Rows[0][0].ToString() == "1")
{
DataTable dtbl2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter("dbo.loginType", sqlCon);
da2.SelectCommand.CommandType = CommandType.StoredProcedure;
da2.SelectCommand.Parameters.AddWithValue("@user", user.Text.Trim());
da2.Fill(dtbl2);
t = dtbl2.Rows[0][0].ToString();
System.Diagnostics.Debug.WriteLine("t is : "+t);
if (t== "A")
{
System.Diagnostics.Debug.WriteLine("innnnnnnn");
this.Hide();
AdminMainForm form = new AdminMainForm();
form.Show();
}
这是我收到的消息之一:
跳过的加载符号。模块已优化,调试器选项“ Just My Code”已启用。
它在if条件-> if (t == "A")...
和
每次点击都只是打印以管理我的行
t is : A
我检查了大小写,并且t等于“ A”。还检查了我的存储过程,查询,一切都很好。 谢谢你的帮助。 迈克尔。
答案 0 :(得分:0)
比较字符串时,请使用if(oneString.Equals(otherString))
。
完整代码:
using(SqlConnection sqlCon = new SqlConnection(Program.cs))
{
sqlCon.Open();
using(SqlDataAdapter da = new SqlDataAdapter("dbo.login", sqlCon))
{
DataTable dtbl = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("@user", user.Text);
da.SelectCommand.Parameters.AddWithValue("@pass", pass.Text);
da.Fill(dtbl);
if (dtbl.Rows[0][0].ToString() == "1")
{
//here rewrite code with using statement
DataTable dtbl2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter("dbo.loginType", sqlCon);
da2.SelectCommand.CommandType = CommandType.StoredProcedure;
da2.SelectCommand.Parameters.AddWithValue("@user", user.Text.Trim());
da2.Fill(dtbl2);
t = dtbl2.Rows[0][0].ToString();
System.Diagnostics.Debug.WriteLine("t is : "+t);
if (t.Equals("A"))
{
System.Diagnostics.Debug.WriteLine("innnnnnnn");
this.Hide();
AdminMainForm form = new AdminMainForm();
form.Show();
}
}
}
}
关闭主题:同样,在连接数据库时,也应这样:
using(SqlConnection con ....)
{
con.Open();
using(SqlCommand cmd....)
{
...
}
}
之所以需要使用它,是因为SqlConnection, SqlCommand ....
是IDisposable
,并且在using
语句中您随后将其处理,这样就释放了内存,因此无需执行{{1} }
答案 1 :(得分:0)
问题解决了。 我用t.toCharArray()然后打印到控制台,它是一个字符“ A”和20个空格。 db中的数据类型为char(1)。 所以我用char x = t.CharAt(0)。