我有什么:
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
Dim curItem As String = ChooseProgram.SelectedItem.ToString()
End Sub
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curitem.string")
jhin.Close()
End Sub
我只想将字符串写入文件。 怎么可能?
谢谢你的帮助! Hannir
更新:
' Ensure an item is selected
If ChooseProgram.SelectedItem Is Not Nothing Then
curItem = ChooseProgram.SelectedItem.ToString()
End If
我在这里收到错误。
" Is运算符不接受类型为&#34的操作数;整数" 。操作数必须是引用类型,或者允许类型,NULL值。"
真的是你的快速帮助! @Pro Grammer
如果您只是单击“安装”,并且未选择任何内容,则会以错误结束。所以可以说"你需要在"之前选择一个项目。或者只有在选择项目时才能点击安装按钮?
答案 0 :(得分:2)
这是一个选择:
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim curItem as String = ""
' Ensure an item is selected
If ChooseProgram.SelectedItem IsNot Nothing
curItem = ChooseProgram.SelectedItem.ToString()
End If
' Double checking valid input
If String.IsNullOrWhiteSpace(curItem) Then
' Handle empty input - Display message, etc
' Exit Sub (unless bat handles empty)
End If
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
jhin.Close()
End Sub
您可以从这里处理它,而不是使用ChooseProgram_SelectedIndexChanged
事件,因为您没有在该方法中执行任何其他操作。如果您仍想使用该事件,则可以将字符串值分配到可在整个类中访问的字段中。查看此示例的Visual Vincent's answer以及Using
块,这样就无需手动调用jhin.Close()
,也可以提供更清晰的格式
答案 1 :(得分:2)
对于初学者,您必须将curItem
变量的声明移出SelectedIndexChanged
方法,转到类级别。
目前,您的变量只能在SelectedIndexChanged
方法中访问,而如果您将其移动到类级别,则该类中的所有内容都可以访问它(本例中的类是您的表单)。然后,您只需从SelectedIndexChanged
方法修改变量。
Dim curItem As String = "" 'We'll start with an empty string.
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
curItem = ChooseProgram.SelectedItem.ToString()
End Sub
现在,您将能够从按钮访问变量并将其写入文件。
您要做的最后一件事是关闭您创建的StreamWriter
,以便释放文件上的锁定。最简单,最好的方法是将其包装在Using/End Using
块中。
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Using jhin As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
End Using
End Sub
修改强>
要仅在选择项目时使按钮可单击,首先通过设计器中的属性窗口将按钮的Enabled
属性设置为False,然后在SelectedIndexChanged
中使用此代码事件:
Install.Enabled = ChooseProgram.SelectedIndex >= 0
If ChooseProgram.SelectedIndex < 0 Then Return
curItem = ChooseProgram.SelectedItem.ToString()