我正在使用C#构建一个Windows应用程序.在我的登录表单中,我在调用fill方法之前没有初始化Select Command属性.
这是代码:
public partial class frmlogin : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter();
public frmlogin()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = con;
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
frmmain main = new frmmain();
main.Show();
}
else
{
MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ari*_*rie 14
在填充表之前,必须指定SqlDataAdapter的select命令.你没有这样做.您的SqlCommand对象未以任何方式连接到您的SqlDataAdapter.
adp.SelectCommand=cmd;
Run Code Online (Sandbox Code Playgroud)
小智 7
另一种完成方法是简单地将 SQLCommand 作为参数传递到您的数据适配器中,如下所示 -
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
Run Code Online (Sandbox Code Playgroud)