2012-05-29 47 views
0

我有一個將信息提交給Access數據庫的C#應用​​程序。我填寫三個必填框,然後單擊「提交」。當使用單擊按鈕時,腳本應按以下方式響應:我的程序似乎在跳過我的「If」語句

第1步。查看數據庫表A,查看數據庫中是否存在textBox1中的值。

第2步。如果該值存在,則分別將textBox1,textBox2和textBox3的值分別添加到數據庫表B列中。

第3步。如果三個文本框中的任何一個留空,顯示一條消息。

第4步。如果textBox1中的值不在數據庫表中,則顯示一條消息。 (最終,我打算在與數據庫字段的默認人口替換消息)

該問題:當我運行該程序,在上述任何情況下,結果是上述步驟號4中。它似乎跳過了第一個「if」聲明,並跳到了「其他」結果。

任何幫助解決此問題,將不勝感激!下面是「Private Void」代碼。 在此先感謝。


private void button1_Click(object sender, EventArgs e) 
{ 
    OleDbCommand cmd = new OleDbCommand("select * from script_Orders where cust_Name = @UserID", vcon); 
    OleDbParameter param = new OleDbParameter(); 
    param.ParameterName = "@UserID"; 
    param.Value = textBox1.Text; 
    cmd.Parameters.Add(param); 
    OleDbDataReader reader = cmd.ExecuteReader(); 
    {  
     if (reader.HasRows) 
     { 
      if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "") 
      { 
       MessageBox.Show("You must fill in all fields."); 
       return; 
      } 
      else 
      { 
       OleDbCommand dbCommand; 
       OleDbDataReader dbReader; 
       new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Search\Database.accdb"); 
       dbCommand = new OleDbCommand("select count(*) as Record_Count from script_received", vcon); 
       dbReader = dbCommand.ExecuteReader(); 

        if (dbReader.Read() == true) 
         rowCount = dbReader["Record_Count"].ToString(); 
        else 
         return; 

        var date = DateTime.Now.ToString("MM/dd/yyyy"); 
        { 
         using (OleDbCommand command = new OleDbCommand("INSERT INTO script_Received (script, qty, emp_id, received_Date) VALUES (@script,@qty,@emp_Id,@rec_date)")) 
         { 
          command.CommandType = CommandType.Text; 
          command.Parameters.Add("@script", OleDbType.Integer).Value = textBox1.Text; 
          command.Parameters.Add("@qty", OleDbType.VarChar).Value = textBox2.Text; 
          command.Parameters.Add("@emp_id", OleDbType.VarChar).Value = textBox3.Text; 
          command.Parameters.Add("@rec_date", OleDbType.Date).Value = date; 
          command.Connection = vcon; 
          command.ExecuteNonQuery(); 
         } 
         this.textBox1.Clear(); 
         this.textBox2.Clear(); 
         this.textBox1.Focus(); 
        } 
      } 
     } 
     else 
     { 
      MessageBox.Show("The value of textBox1 is not in the orders table"); 
      return; 
     } 
    } 
} 
+2

當你調試時會發生什麼?有錯誤嗎?對條件進行評估時,對象的狀態是什麼?也許價值是不同於你的期望? – David

+9

現在這是一個非常嚴重的縮進濫用案例。 –

+1

我懷疑如果你真的調試過這個東西,你會發現'reader'是'null' ...你爲什麼這麼認爲? *提示提示:*仔細查看你的連接樣板代碼,你錯過了*某事* ... – Didaxis

回答

2

如果跳轉到if(reader.HasRows)else沒有拋出任何異常,那麼reader切不可null,這是HasRows屬性必須是false。這意味着您的查詢成功執行,但不返回任何行。

您可能會嘗試手動運行select聲明,這可能會幫助您瞭解錯誤。很可能,您在文本框中輸入的內容與cust_name的任何值都不匹配。