遍历 ListBox 的所有 selectedValues

iterate through all the selectedValues of ListBox

我正在使用 C# 编写 windows 表单应用程序。我有一个具有多选能力的列表框。如何获取所有选定值的值?

  sql = " Select Division.* from Division ";
  DataTable divisionTable = client.GetDataTable(null, sql,  null);
  divisionListBox.DataSource = divisionTable;
  divisionListBox.DisplayMember = "Name";
  divisionListBox.ValueMember = "BValue";                   
  divisionListBox.SelectedIndex = -1;

我想遍历所有选中的值并得到它们的 BValue 的总值。

谢谢

我想我明白了 这就是答案

  int total = 0;
  foreach (System.Data.DataRowView item in divisionListBox.SelectedItems) 
  {
     total += item.Row.Field<int>(2) ;
  }

(2)表示sql句中的BValue。 sql 的结果就像

Id, 名称, B值

所以我想要 BValue,我应该使用 (2)

使用绑定到数据表的 LB 包含的 SelectedItems property, and it'll play nice with LINQ if you cast it to the DataRowView 个对象。 (LB 绑定到 datatable.DefaultView,这是一个 DataView,因此是 DataRowView 元素。DataRowView 有一个接受列名的项目索引器):

var total = listBox1.SelectedItems.Cast<DataRowView>().Sum(drv => (int)drv["BValue"]);

如果您的数据表是强类型的:

var total = listBox1.SelectedItems.Cast<DataRowView>().Sum(drv => (drv.Row as StronglyTypedRowName).BValue);

..这更好,因为它避免了字符串索引,并且意味着如果您在代码中重命名 BValue,它将更新