C# 如何获取listbox的选定索引的值
这段代码填充列表框,当我试图从所选索引中获取值时,我似乎找不到获取索引值的方法。这段代码可能会对您有所帮助C# 如何获取listbox的选定索引的值,c#,listbox,sql-server-express,population,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=L
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;
}
}
}
}
现在还不清楚您想做什么您有
KALORİokuyucu
它将保存SqlDataReader
对象的值`如果您想获得分配给lblKalori
的值,您应该执行lbİKalori.Items。添加((字符串)KALORİokuyucu[“FieldNameYouWant]”)
另外,您是否确定在分配给标签时只返回1项
?否则,如果返回多条记录,您将覆盖上一个分配意味着您需要更改对ExecuteScalar()的.ExcuteReader()调用
为什么不使用块将baglanti2
的实例化放入中?
// 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);`