2017-04-17 75 views
0
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    SqlConnection sqlcon1 = new SqlConnection(@"Data Source=PRATHISTA;Initial Catalog=CRMT;Integrated Security=True"); 
    sqlcon1.Open(); 
    SqlCommand cmd1 = new SqlCommand("select * from Requirement", sqlcon1); 
    try 
    { 
     SqlDataReader sda1 = cmd1.ExecuteReader(); 
     while (sda1.Read()) 
     { 
      string sId = sda1.GetString("Requirement_Id"); 
      // i get the error here; 
     } 
     sda1.Close(); 
     sqlcon1.Close(); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show("Error:" + ex); 

    } 
} 
+0

似乎'Requirement_Id'是' int',而不是'string'。試試'int id = sda1.GetInt32(「Requirement_Id」)'。 –

+1

如果'sda1.GetString(「Requirement_Id」)1 null,則在分配之前檢查'!SqlReader.IsDBNull(「Requirement_Id」)'。 – Anil

+0

您可以添加表列的數據類型嗎?可能'Requirement_Id'不是一個字符串。 –

回答

0

當你的id列不是字符串,數據庫不返回一個字符串 - 你只能使用GetString方法對於字符串列。您現在有兩個選擇:

  1. 使用GetInt32
  2. 直接從讀者

第一個選項就是這樣做獲得的數據:但是

var sId = sda1.GetInt32(index); 

記住指數這裏不能是字符串類型,並且必須是整數。

第二個選項是在這種情況下更好的(在我看來):

var sId = (int)sda1["Requirement_Id"]; 

你可以(當然)仍然使用的字符串:

var sId = sda1["Requirement_Id"].ToString(); 
+0

非常感謝我的工作! –