我正在使用C#構建一個Windows應用程序。在我的登錄表單中,我得到了在調用填充方法之前,選擇Command屬性尚未初始化。在調用'Fill'之前,SelectCommand屬性尚未初始化。在WinForm中
下面是代碼:
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);
}
}
}
您需要將'SqlCommand'對象分配到'SqlDataAdapter' - 只是就像錯誤說的那樣。 :)請查看參數化查詢 - 因爲您的代碼現在已經成熟,適用於SQL注入。 – Tim 2013-04-04 06:22:49