将每个新字符串添加到现有的字符串列表中

时间:2013-01-15 13:50:49

标签: asp.net vb.net

我正在尝试将gridview的templateFields'值添加到List(Of String)中。那些templateFields由2 Labels组成。我想要实现的是

  1. 为了能够遍历GridView的每一行,获取重复的templateField值。

  2. 将行的TemplateFields1值存储在字符串中。

  3. 将该字符串添加到字符串列表中。

  4. 这是我的代码:

    For Each row As GridViewRow In GridView1.Rows`
        Dim stri As String
        Dim ttt As Label = DirectCast(row.FindControl("Title"), Label)
        Dim desc As Label = DirectCast(row.FindControl("lblDescription"), Label)
        stri = ttt.Text.ToString & desc.Text.ToString
        Dim list As New List(Of String)
        While (stri <> Nothing) 
            list.Add(stri)  ' Add every new string in a new index of the list 
        End While
    Next
    

    因此,在while循环中,stri将其存储在list(0)中,然后继续for loop,获取下一个stri并将其存储在list(1)list(0)的新索引,同时保留templateField stri等等,直到所有{{1}}完成。

    有什么想法或建议吗?

1 个答案:

答案 0 :(得分:1)

您必须在循环外创建列表。我还用While语句替换If循环:

Dim list As New List(Of String)

For Each row As GridViewRow In GridView1.Rows
    Dim ttt As Label = DirectCast(row.FindControl("Title"), Label)
    Dim desc As Label = DirectCast(row.FindControl("lblDescription"), Label)
    Dim stri As String = ttt.Text.ToString & desc.Text.ToString

    If (Not String.IsNullOrEmpty(stri)) 
        list.Add(stri)
    End If
Next