2013-04-08 223 views
0
string KaloriSorgusu = "use FoodDB select drink_kal from Drinks"; 
SqlConnection baglanti2 = new SqlConnection("Data Source=" + IPFORM.ip.ToString() + "\\SQLEXPRESS;Initial Catalog=UserDB;User Id=Levent; Password=21012101;Trusted_Connection=False;Integrated Security=False"); 
using (baglanti2) 
{ 
    using (SqlCommand KaloriKomutu = new SqlCommand(KaloriSorgusu, baglanti2)) 
    { 
     baglanti2.Open(); 
     using (SqlDataReader KALORİokuyucu = KaloriKomutu.ExecuteReader()) 
     { 
       while (KALORİokuyucu.Read()) 
       { 
        lb_Kalori.Items.Add(KALORİokuyucu.GetValue(0).ToString()); 
        total = lb_Kalori.Items.Count; 
       } 
     } 
    } 
} 

的選擇指標的值此代碼填充列表框,當我試圖從選定的指數值,我似乎無法找到一種方式來獲得的指數值。我怎樣才能獲得列表框

+0

目前還不清楚你想幹什麼,你有'KALORİokuyucu'如果你想分配給'lblKalori'你應該做'lb_Kalori該值將從'SqlDataReader' Object'保存值現在是什麼.Items.Add((string)KALORİokuyucu[「FieldNameYouWant」]);'你也確定只有'1 Item'在分配給標籤時會被返回嗎?否則如果返回多個記錄,則將覆蓋以前的分配。 '這意味着你需要將.ExcuteReader()調用改爲ExecuteScalar()' – MethodMan 2013-04-08 19:01:12

+1

爲什麼不把'baglanti2'的實例化放入'using'塊? – 2013-04-08 19:03:11

回答

0

可能是這個小片段將幫助你。

// Get the currently selected item in the ListBox. 
    string curItem = listBox1.SelectedItem.ToString(); 

// Find the string in ListBox2. 
    int index = listBox2.FindString(curItem); 
// If the item was not found in ListBox 2 display a message box, otherwise select it in  ListBox2. 
if(index == -1) 
    MessageBox.Show("Item is not available in ListBox2"); 
else 
    listBox2.SetSelected(index,true);`