2013-04-04 331 views
6

我正在使用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); 
     } 
    } 
} 
+0

您需要將'SqlCommand'對象分配到'SqlDataAdapter' - 只是就像錯誤說的那樣。 :)請查看參數化查詢 - 因爲您的代碼現在已經成熟,適用於SQL注入。 – Tim 2013-04-04 06:22:49

回答

13

你盡顯你的桌子前指定的SqlDataAdapter的select命令。你沒有這樣做。你的SqlCommand對象沒有以任何方式連接到你的SqlDataAdapter。

adp.SelectCommand=cmd; 
1

另一種方式來完成是簡單地傳遞的SqlCommand作爲參數傳遞到您的數據適配器如下 -

SqlCommand cmd = new SqlCommand(); 
SqlDataAdapter adp = new SqlDataAdapter(cmd); 
相關問題