如何获取所选列表框索引的值

时间:2013-04-08 18:53:28

标签: c# listbox sql-server-express population

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;
              }
         }
     }
}

此代码填充列表框,当我尝试从所选索引中获取值时,我似乎无法找到获取索引值的方法。

1 个答案:

答案 0 :(得分: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);`