lulutanseco lulutanseco - 4 months ago 35
ASP.NET (C#) Question

GridView Reader returns repeating values ASP.NET

I am trying to create a datatable that contains items I read from a GridView column.
The GridView I'm reading looks like this:

SELECT COURSE NAME

Select Course_1 USER_1
Select Course_2 USER_2
Select Course_3 USER_3


This is my code:

Dim dt As New DataTable()
Dim dtcopy As New Datatable()

dt.Columns.Add("File",GetType(String))

For Each row As GridViewRow In GV_PDBC.Rows
For i As Integer = 1 To GV_PDBC.Rows.Count - 1
strname = row.Cells(2).Text
dt.Rows.Add(strname)

dtcopy.Merge(dt, True, MissingSchemaAction.AddWithKey)
Next
Next


It's reading the column repeatedly. Here is the datatable result:

USER_1
USER_1
USER_1
USER_1
USER_1
USER_1
USER_1
USER_2
USER_2
...


I think I am just missing something. Please help. thanks in advance

Answer

The correct way of writing code for this:

Dim dt As New DataTable()
Dim dtcopy As New Datatable()

dt.Columns.Add("File",GetType(String))

'This loop will iterate all gridview rows
For Each row As GridViewRow In GV_PDBC.Rows 

    'Determine the row type.
    if row.RowType = DataControlRowType.DataRow Then
        strname = row.Cells(2).Text
        dt.Rows.Add(strname)
    End If
Next