简体   繁体   English

如何将两个ListBox的项目(代表数字)的值相加

[英]How to add the value of items (representing numbers) of two ListBoxes

I'm trying to add two integers ( X and Y ) from different ListBoxes and show the total in a Label or TextBox.我正在尝试从不同的 ListBoxes 添加两个整数( XY ),并在 Label 或 TextBox 中显示总数。

I've tried copying the code from answered questions and emending to suit my code, but still struggling.我已经尝试从已回答的问题中复制代码并进行修改以适合我的代码,但仍在苦苦挣扎。

Dim lblTotal As Integer 
Dim X, Y As Integer 
Const WasGo = 35 
Const Vacuum = 20  

' The item description from the ListBox are supposed to be Constants
X = extBox.SelectItems(0) 
Y = intBox.SelectItems(0) 
lblTotal = X + Y

ListBox has a SelectedItems property. ListBox 有一个 SelectedItems 属性。 Assuming you have exactly one selected from each, this should work:假设您从每个中选择了一个,这应该有效:

X = Convert.ToInt32(extBox.SelectedItems(0).ToString())
Y = Convert.ToInt32(intBox.SelectedItems(0).ToString())
lblTotal = X + Y

Few other tips/questions.很少有其他提示/问题。

  • I don't know what extBox, intBox, x and y are.我不知道 extBox、intBox、x 和 y 是什么。 Make sure your names are well defined.确保你的名字定义明确。
  • Checking against the index of an array is good (If extBox.SelectedItems.Length > 0 Then), but then you need a way to handle that condition.检查数组的索引是好的(如果 extBox.SelectedItems.Length > 0 Then),但是你需要一种方法来处理这种情况。 Maybe you need a prompt if nothing was selected如果未选择任何内容,可能需要提示
  • What are you doing with an integer labeled lblTotal?你在用一个标有 lblTotal 的 integer 做什么? Is this getting displayed somewhere?这是在某处显示吗?
  • I'm assuming your listboxes both contain a list of integers.我假设您的列表框都包含整数列表。

You don't use those constants in this code.您不在此代码中使用这些常量。 Convert the items to Integers so you can perform addition.将项目转换为整数,以便您可以执行加法。 To display in a label's text property call .ToString on the Integer要在标签的文本属性中显示,请在 Integer 上调用.ToString

Private Sub OPCode()
    Dim lblTotal As Integer
    lblTotal = CInt(extBox.SelectItems(0)) + CInt(intBox.SelectItems(0))
    Label1.Text = lblTotal.ToString
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM