首页 > 解决方案 > 如何编辑这个循环?

问题描述

我写了一小段代码,它不能像我想要的那样工作。我的目标:

我有一个 3 行的文本框。每行 = 一个产品。我有第二个文本框,有 2 行。每行 = 1 个产品的变体。

我的结果应该是这样的:

人造草 | 红色的

人造草.1 | 蓝色的

暗孔板| 红色的

暗孔板.1 | 蓝色的

测试孔板| 红色的

测试孔板.1 | 蓝色的

我有这段代码(为你删除了所有不必要的参数):

For value1 As Integer = 0 To NumberOfArticles - 1           
    Dim Name As String = ProductTB.Lines(value1)              
    Dim Variants As String = VariantsTB.Lines(value1)

    For value2 As Integer = 1 To VariantsCountTB.Text - 1    'TextBox with number of variants                                  
        DataGridView1.Rows.Add(New String() { VariantsTB.Lines(value2 - 1)}) 
        DataGridView1.Rows.Add(New String() {VariantsTB.Lines(value2)}) 
    Next

    If value1 = NumberOfArticles Then
        Exit For
    End If
Next

名称是产品文本框的每一行。Variants 是变体 TextBox 的每一行。

问题:它有效,但前提是有与产品一样多的变体。但我只需要 2 个变体,但需要 3 个产品。那么,在哪里编辑这个循环呢?

非常感谢!:)

此致

标签: vb.netloopsfor-loop

解决方案


正如 jmcilhinney 提到lines()的,用于将文本框文本保存在数组中,然后在同一数组上进行循环

''Get all Products in array
Dim products As String() = ProductTB.Lines()
''Get all attributes in array
Dim attrributes As String() = VariantsTB.Lines()
''Create as list for result
Dim resultlist As New List(Of String)

''Loop over product
For Each prod As String In products

    ''Loop over Attributes
    For Each atr As String In attrributes
        Dim resultprd = prod & "|" & atr
        resultlist.Add(resultprd)
    Next

    '' if you want proiducts without attributes also add here 
    ''resultlist.Add("Prod")
Next

推荐阅读