2014-03-26 43 views
-1

我的代碼中的最後一個字符串有問題。使用SqlDataReader時「數據爲空」

這是我的代碼:

private void comboLname_SelectedIndexChanged(object sender, EventArgs e) 
{ 
      string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*****"; 
      string Query = "select * from RMSCRMTest.dbo.sales where LastName= '" + comboLname.Text + "' ;"; 


      SqlConnection Myconn = new SqlConnection(conn); 
      SqlCommand cmdDataBase = new SqlCommand(Query, Myconn); 
      SqlDataReader Reader; 
      try 
      { 
       Myconn.Open(); 
       Reader = cmdDataBase.ExecuteReader(); 
       while (Reader.Read()) 
       { 
        string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString(); 
        string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber")).ToString(); 
        string Time = Reader.GetDateTime(Reader.GetOrdinal("Time")).ToString(); 
        string Deposit = Reader.GetDecimal(Reader.GetOrdinal("Deposit")).ToString(); 
        string slastname = Reader.GetString(Reader.GetOrdinal("lastname")); 
        string sstatus = Reader.GetString(Reader.GetOrdinal("status")); 
        txtid.Text = ID; 
        txtacnum.Text = AccountNuber; 
        txttime.Text = Time; 
        txtdeposit.Text = Deposit; 
        txtlname.Text = slastname; 
        txtstatus.Text = status; 

       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
      finally 
      { 
       Myconn.Close(); 
      } 
} 

這個問題說明,因爲我添加另一列到我的表,並創建的字符串到列 串

sstatus = Reader.GetString(Reader.GetOrdinal("status")); 

我得到的錯誤是

data is null此方法或屬性無法在空值上調用

其他字符串正常工作。

回答

7

您需要使用SqlDataReader.IsDBNull方法檢查可空字段:

int statusIndex = Reader.GetOrdinal("status"); 
string sstatus = Reader.IsDBNull(statusIndex) ? null : Reader.GetString(statusIndex); 
+0

我代替我與你行,我得到「無法投型‘system.Int32’的對象輸入系統字符串'」 – Motimash

+0

對不起,我沒有做對了,讓我再次檢查,並會回來給你謝謝 – Motimash

+0

它工作非常感謝你,請你能解釋爲什麼我不得不添加int作爲此列是varchar,我真的很新這個世界 – Motimash