我是C#的新手。我创建了登录界面。我无法检查用户名和密码。这是我的代码。任何人都可以帮我。谢谢。请不要犹豫,复制代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace Voting_Editor_Tool
{
public partial class Form1 : Form
{
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string username = txtusername.Text;
string password = txtpassword.Text;
if (ValidateUserNamePassword(username, password))
{
// move to next form or do whatever you need to do after a successfull login
}
else
{
MessageBox.Show("Invalid user name or password", "Invalid Login");
return;
}
}
public bool ValidateUserNamePassword(string _username, string _password)
{
// string connectionString = "Data Source=[servername];Initial Catalog=[databaseName];User ID=[Admin Login];Password=[Admin Password];";
using (SqlConnection cn= new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dish_tv;Data Source=ENMEDIA-CCDDFE5\ENMEDIA"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "tsp_GetUserNameAndPassword";
SqlParameterCollection sqlParams = cmd.Parameters;
sqlParams.AddWithValue("@username", _username);
sqlParams.AddWithValue("@password", _password);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
// this will return true if a row matching the username and password is found.
// this means that the user's input is valid
return true;
}
else
{
return false;
}
dr.Close();
cn.Close();
}
}
}
}
答案 0 :(得分:2)
您在using语句的末尾有一个分号,因此终止使用。删除分号,它将起作用。
答案 1 :(得分:2)
删除你的using子句并将那段代码放入Try .. catch块。捕获异常对象并读取其stacktrace
。检查连接字符串是否有任何拼写错误。这应该给你提供更多的调试细节,而不是像“对象引用没有设置为对象的实例”这样的通用错误