Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取listbox的选定索引的值_C#_Listbox_Sql Server Express_Population - Fatal编程技术网

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);`