【发布时间】:2016-06-14 10:13:49
【问题描述】:
首先,我设置 DataTable,如下所示。添加了 3 列,包含 Desc、Price 和要显示的完整字符串。
checkBoxDT = New DataTable
checkBoxDT.Columns.Add(New DataColumn With
{.ColumnName = "Desc", .DataType = GetType(String)})
checkBoxDT.Columns.Add(New DataColumn With
{.ColumnName = "Price", .DataType = GetType(Decimal)})
checkBoxDT.Columns.Add(New DataColumn With
{.ColumnName = "DisplayText", .DataType = GetType(String),
.Expression = "Desc + ' - RM ' + Price"})
然后,我创建一个新的数据视图并将 CheckedListBox1 绑定到 DataTable。
checkListView = New DataView(checkBoxDT)
checkListView.Sort = "Desc ASC, Price ASC"
CheckedListBox1.DataSource = checkListView
CheckedListBox1.DisplayMember = "DisplayText"
这里我使用下面的代码向 CheckedListBox1 添加新项目
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim quan As Integer = 0
Dim currentPrice As Decimal = 0.0
If ComboBox2.SelectedIndex > 0 Then
quan = Convert.ToInt32(ComboBox2.Text.Trim())
currentPrice = Convert.ToDecimal(TextBox3.Text.Trim())
For i As Integer = 1 To quan
checkBoxDT.Rows.Add({ComboBox1.Text, Convert.ToDecimal(TextBox3.Text)})
totalItems = totalItems + 1
totalPrice = totalPrice + currentPrice
Next
Else
currentPrice = Convert.ToDecimal(TextBox3.Text.Trim())
checkBoxDT.Rows.Add({ComboBox1.Text, Convert.ToDecimal(TextBox3.Text)})
totalItems = totalItems + 1
totalPrice = totalPrice + currentPrice
End If
TextBox5.Text = totalItems.ToString()
TextBox4.Text = totalPrice.ToString()
End Sub
但我在删除 CheckedListBox1 项目时遇到问题。这是我尝试过的。
这是删除按钮。我正在尝试删除 CheckedListBox1 中所有选定项目的项目。然后在 TextBox4 中显示正确的价格。当我只选择要删除的一项时,它工作正常。但是选择的多个项目无法正常工作。它也会删除其他未被选中的项目。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim currentPrice As Decimal = 0.0
While CheckedListBox1.CheckedItems.Count > 0
currentPrice = Convert.ToDecimal(CType(CheckedListBox1.SelectedItems(0), DataRowView).Item("Price").ToString())
totalPrice = totalPrice - currentPrice
totalItems = totalItems - 1
checkListView.Delete(CheckedListBox1.SelectedIndex())
End While
TextBox4.Text = totalPrice.ToString()
TextBox5.Text = totalItems.ToString()
End Sub
【问题讨论】:
-
试试这个:vbcity.com/blogs/xtab/archive/2010/09/22/… 而不是 delete 使用 remove
-
@coder32 我已经看过指南了。仍然无法做我想做的,所以我在这里发布了一个问题。
标签: vb.net datatable visual-studio-2015 dataview checkedlistbox