【问题标题】:VB.NET certain variables will not apply visually to CheckBox or RadioButton.TextVB.NET 的某些变量不会在视觉上应用于 CheckBox 或 RadioButton.Text
【发布时间】:2016-03-17 07:58:32
【问题描述】:

我正在尝试使表单从文本文件的行中填充 RadioButton 选项。

我有代码为文本文件的每一行动态声明数组中的变量:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
    Dim cnt As Integer = 0
    For Each c As Char In value
        If c = ch Then cnt += 1
    Next
    Return cnt
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim output As String
    Dim lineCount As Integer = 0
    Dim classText As String = "(text file path)"
    output = IO.File.ReadAllText(classText)
    'declare text file to variable
    lineCount = CountCharacter(output, vbCrLf) + 1
    'get line count (delimited by line feed)
    Dim strLine() As String = output.Split(vbCrLf)
    'split output variable delimited by line feed
    Dim classSelection(lineCount) As String
    'declare string array for amount of lines
    Dim period As Integer = 0
    'declare integer for counting 'For Each' statement
    For Each line As String In strLine
        period += 1
        'count one 'For Each' rotation period
        classSelection(period) = line
        'dynamically declare array data based on line/rotation number
    Next

现在我应该为每一行设置 classSelection()

当我尝试将其传递给 RadioButtons 或 CheckBoxes 时,只有第一行 classSelection(1) 可显示为 RadioButton.Text 例如:

RadioButton1.Text = classSelection(1)
RadioButton2.Text = classSelection(2)
RadioButton3.Text = classSelection(3)

这将在 RadioButton1 上显示文本文件的第一行,在 RadioButton2 和 3 上为空白。我可以将 classSelection(1) 传递给三个 RadioButtons 中的任何一个,它也会显示在它们上,但是 classSelection(2 ) 或 classSelection(3) 将不会显示在任何 RadioButtons 上。 对我来说奇怪的是 RadioButton2.Text 持有 classSelection(2) 的值,只是不显示它。因为我可以将不显示的 RadioButton2.Text 的值传递给另一个对象,classSelection(2) 的值就会很好地显示在它上面。

是什么让 classSelection(1) 与 classSelection(2) 如此不同以使其不显示?

【问题讨论】:

  • 不是没有,但如果您使用组合框:theCBO.Items.AddRange(File.ReadAllLines(someFile)) 就是您所需要的

标签: vb.net radio-button


【解决方案1】:

问题在于您拆分阅读的String 的方式。这是为什么您应该拥有Option Strict On 的完美示例。当您拥有Option Strict Off 时,代码可能会以意想不到的方式执行。这里:

Dim strLine() As String = output.Split(vbCrLf)

您大概认为您正在拆分成对的回车符和换行符。你不是。 String.Split 的重载仅接受 Char 分隔符,而不接受 String 分隔符。如果你有Option Strict On,那么你就会被警告过。事实上,编译器只是假设您想使用String 中的第一个Char。因此,换行符被丢弃,并且仅在回车符上完成拆分。这意味着结果数组的第一个元素之后的每个元素都将以换行开始。

如果您真的想在String 分隔符上进行拆分,那么您必须调用接受String 分隔符的Split 的重载。会是这样的:

Dim strLine() As String = output.Split({vbCrLf}, StringSplitOptions.None)

说了这么多,既然你可以打电话给File.ReadAllLines,你为什么还要麻烦打电话给File.ReadAllText,然后在换行符处拆分呢?

【讨论】:

  • 读到这里,现在很有意义。您的意见解决了我的困境,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 2018-03-08
  • 2016-04-01
  • 2014-03-24
相关资源
最近更新 更多