代码之家  ›  专栏  ›  技术社区  ›  user3580480

拆分HTML表的逗号分隔值

  •  1
  • user3580480  · 技术社区  · 7 年前

    我有一个由逗号分隔的2列表格,如下所示:

    |----------------|---------------------| 
    |  description   |        price        |
    |----------------|---------------------|            
    |    A,B,C,D     |    £1,£4,£7,£1.50   | 
    |----------------|---------------------|           
    |    D,F,A,G     |     £4,£8,£9,£10    | 
    |----------------|---------------------|
    

    我正在尝试构建一个html字符串,以将上述逗号分隔的值添加到html表中。如下所示:

    |----------------|---------------------| 
    |  description   |        price        |
    |-----------   --|---------------------|            
    |        A       |          £1         | 
    |----------------|---------------------|           
    |        B       |          £4         | 
    |----------------|---------------------|   
    |        C       |          £7         | 
    |----------------|---------------------|   
    |        D       |       £1.50         | 
    |----------------|---------------------|   
    |        D       |          £4         | 
    |----------------|---------------------|   
    |        A       |          £8         | 
    |----------------|---------------------|   
    |        F       |          £9         | 
    |----------------|---------------------|   
    |        G       |         £10         | 
    |----------------|---------------------|   
    

    我目前有下面的代码,它适用于描述字段,但我不确定如何获取价格值。

    我是否需要为每列设置单独的FOR循环?

    For Each Product As String In Form1.DataGridView1.CurrentRow.Cells(2).Value.ToString.Split(", ")
        Products.AppendLine(String.Format("     <tr>{0}
                                                <td>{1}</td>{0}
                                                </tr>", Environment.NewLine,
                                                Product))
    
    Next Product
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   MatSnow    7 年前

    尝试以下操作:

    Dim Products As New System.Text.StringBuilder
    
    For Each row As DataGridViewRow In DataGridView1.Rows
        Dim colA As String() = row.Cells(2).Value.ToString.Split(","c)
        Dim colB As String() = row.Cells(3).Value.ToString.Split(","c)
    
        For i As Integer = 0 To Math.Max(colA.Length, colB.Length) - 1
            Products.AppendLine("<tr>")
            Products.AppendLine(String.Format("<td>{0}</td><td>{1}</td>",
                                                If(i > colA.Length - 1, "", colA(i)),
                                                If(i > colB.Length - 1, "", colB(i))
                                             )
                               )
            Products.AppendLine("</tr>")
        Next
    Next
    

    如果同一行上的描述数和价格不同,这仍然有效。