如何使用if语句与包含strName字符串的列表框进行比较 [英] How to compare with ListBoxes that contains string for strName using if statements
问题描述
我是编程的初学者,现在我在大学里正在讲视觉基础的编程课程,而且我正在写一个有关CD Collection的程序,该程序可以防止用户将CD名称复制到列表框中.三种类型是CD名称,艺术家和价格.
现在,我输入其中三个(使用输入框)以添加并存储到列表框(链接到"names.txt"文件).
现在,我想添加另外三个,当他们问我CD名称时,如果我键入与已经存储在列表框中的CD名称相同的CD名称,它应该显示我已经输入了CD名称.这是我遇到的困难.
如何使用if语句将strName设置为与列表框中的strName进行比较?
任何帮助表示赞赏.
Hi, I''m a beginner of programming and I''m talking visual basic programming course now at college, and I''m writing a program about the CD Collection that prevents user to duplicate CD name into the listbox. The three types are CD name, artists, and price.
Now I input three of those(using inputbox) to add and store into listbox(linked to "names.txt" file).
Now I want to add another three, and when they ask me for the cd name, and if I type the same cd name as the one that is already stored in the listbox, it should display that I already entered the CD name. This is the one I''m having difficult with.
How can I set the strName to compare with the strName''s in the listbox using the if statement?
Any help is appreciated.
Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
' adds CD information to the list box
' declare variables
Dim strName As String
Dim strArtist As String
Dim strPrice As String
Dim strConcatenatedInfo As String
Dim dblPrice As Double
' get the CD information
strName = InputBox("CD name:", "CD Collection")
If strName.Contains(strName.PadRight(40)) Then
MessageBox.Show("Duplicate Name",
"CD Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
Else
strArtist = InputBox("Artist:", "CD Collection")
strPrice = InputBox("Price:", "CD Collection")
' format the price, then concatenate the
' input items, using 40 spaces for the
' CD name, 25 spaces for the artist name,
' and 5 spaces for the price
Double.TryParse(strPrice, dblPrice)
strPrice = dblPrice.ToString("N2")
strConcatenatedInfo = strName.PadRight(40) &
strArtist.PadRight(25) & strPrice.PadLeft(5)
' add the information to the list box
lstCds.Items.Add(strConcatenatedInfo)
End If
End Sub
推荐答案
If strName.Contains(strName.PadRight(40)) Then
您正在尝试将strName与自身进行比较.您想将其与列表框中的现有项目进行比较.
顺便说一句:您在学习时应该指出,匈牙利符号(变量的三个字母前缀)已经过时了几年.
You are trying to compare strName against itself. You want to compare it against existing items in the listbox.
BTW: As you are just learning it should be pointed out that Hungarian notation, the three letter prefix to your variables, has been outdated for several years now.
这篇关于如何使用if语句与包含strName字符串的列表框进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!