如何将独立ListBox的数据与另一ListBox绑定实现选项关联
两个ListBox关联绑定实现方案
你的需求是让食物列表和卡路里列表的对应项永久关联,选中食物时自动匹配对应卡路里,无需手动选择第二个列表,实现方式如下:
实现效果参考



方案1:同步选中索引(轻量改动)
因为你添加食物和卡路里的时候是按顺序成对添加的,同下标位置的项本身就是对应关系,只需要同步两个ListBox的选中索引即可实现绑定。
Public Class Form1 Public strfood As String Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click Dim calory As Single strfood = InputBox("Enter food item", "Food List") calory = InputBox("Enter calory", "Calory List") FoodList.Items.Add(strfood) CaloryList.Items.Add(calory) End Sub ' 新增食物列表选中变化事件,同步卡路里列表的选中项 Private Sub FoodList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FoodList.SelectedIndexChanged ' 加判断避免索引越界报错 If FoodList.SelectedIndex >= 0 AndAlso FoodList.SelectedIndex < CaloryList.Items.Count Then CaloryList.SelectedIndex = FoodList.SelectedIndex End If End Sub Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click ' 优化:直接用索引取值,即使卡路里列表没选中也能拿到对应值,更稳妥 If FoodList.SelectedIndex >= 0 Then Dim selecteditem As String = FoodList.SelectedItem.ToString Dim selectedcalory As String = CaloryList.Items(FoodList.SelectedIndex).ToString MessageBox.Show("Food :" & selecteditem & " " & "Calories :" & selectedcalory) End If End Sub End Class
方案2:数据源绑定(更规范,不易出错)
如果想从数据层面直接关联,避免后续手动同步索引的麻烦,可以用结构化数据源绑定,两个列表绑定同一个数据源,选中会自动同步:
' 先定义食物结构类 Public Class FoodItem Public Property Name As String Public Property Calory As Single End Class Public Class Form1 ' 定义统一的食物数据源 Dim foodDataSource As New List(Of FoodItem) Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click Dim foodName = InputBox("Enter food item", "Food List") Dim caloryVal = Val(InputBox("Enter calory", "Calory List")) foodDataSource.Add(New FoodItem With {.Name = foodName, .Calory = caloryVal}) ' 刷新两个列表的绑定 FoodList.DataSource = Nothing FoodList.DataSource = foodDataSource FoodList.DisplayMember = "Name" CaloryList.DataSource = Nothing CaloryList.DataSource = foodDataSource CaloryList.DisplayMember = "Calory" End Sub Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click If FoodList.SelectedItem IsNot Nothing Then Dim selectedFood = CType(FoodList.SelectedItem, FoodItem) MessageBox.Show($"Food :{selectedFood.Name} Calories :{selectedFood.Calory}") End If End Sub End Class
内容的提问来源于stack exchange,提问作者3llyas
相关产品推荐
相关产品推荐

