如何删除列表框中选定的数据行并使用VB更新相关的文本文件(从文本文件中删除相同的行)? [英] How to delete selected row of data in list box and update the relevant text file (remove the same row from the text file) using VB?

查看:151
本文介绍了如何删除列表框中选定的数据行并使用VB更新相关的文本文件(从文本文件中删除相同的行)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过使用下面的代码,它背后的逻辑看起来很好但是一旦我运行代码它似乎不起作用,它突出显示MyString并说变量在被赋值之前被使用有人有建议吗?提前谢谢。



我尝试过的事情:



如果ListBox1.SelectedItems.Count> 0然后
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
Dim MyString As String
For Count As Integer = 0 To ListBox1.Items.Count - 1
MyString& = ListBox1.Items.Item(Count)& Environment.NewLine
下一个
My.Computer.FileSystem.WriteAllText(Z:\Desktop\ciao.txt,MyString,False)
End if
End Sub

解决方案

正如错误消息所示,您正在读取变量的值 MyString 在第一次转让之前。



首先,如果 ListBox1中没有剩余物品,循环中的代码永远不会执行。当你来到 WriteAllText 行时,变量没有分配给它的值。



其次,在循环内部,您将字符串附加到变量。但这涉及首先读取变量的当前值。在循环的第一次迭代中,没有分配任何值。



快速解决方法是在循环之前分配一个值:

  Dim  MyString  As  字符串 =   



但是,在循环中避免字符串连接通常是个好主意。根据列表中的项目数,您可能希望使用 StringBuilder 循环[ ^ ]构建字符串。


I have tried using the code below, the logic behind it seems to be fine but it does not seem to work once I run the code,it highlights "MyString" and says " variable is used before it has been assigned a value" has anyone got suggestions?Thank you in advance.

What I have tried:

If ListBox1.SelectedItems.Count > 0 Then
           ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
           Dim MyString As String
           For Count As Integer = 0 To ListBox1.Items.Count - 1
               MyString &= ListBox1.Items.Item(Count) & Environment.NewLine
           Next
           My.Computer.FileSystem.WriteAllText("Z:\Desktop\ciao.txt", MyString, False)
       End If
   End Sub

解决方案

As the error message says, you are reading the value of the variable MyString before the first assignment to it.

Firstly, if there are no items left in ListBox1, the code inside your loop will never execute. When you come to the WriteAllText line, the variable has not had a value assigned to it.

Secondly, inside the loop, you're appending a string to the variable. But that involves reading the current value of the variable first. On the first iteration of the loop, no value has been assigned.

The quick fix is to assign a value before the loop:

Dim MyString As String = ""


However, it's generally a good idea to avoid string concatenation in a loop. Depending on the number of items in your list, you might want to loop at using a StringBuilder[^] to build the string.


这篇关于如何删除列表框中选定的数据行并使用VB更新相关的文本文件(从文本文件中删除相同的行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆