简体   繁体   中英

Adding new row to unbound datagridview

I have an unbound datagridview. Because of the various things I am doing with the data in the grid I do not want to bind it. The columns are predefined in the settings (Edit Columns) of the datagridview. I want to create a new row and then populate the grid row with data. I am trying to use the .Add.Rows method but it is failing with

{"Index was out of range. Must be non-negative and less than the size of the collection." & vbCrLf & "Parameter name: index"}

The following SQL retrieves data:

USE CCAP
declare @ScheduleName as varchar(30) = 'Walk-In Center April Wk 1 2019'
Select ShiftName, ScheduleStart, ScheduleEnd, Position, ADP_ID1,
       Name1,ADP_ID2, Name2, ADP_ID3, Name3, ADP_ID4, Name4, ADP_ID5,
       Name5, ADP_ID6, Name6, ADP_ID7, Name7 
from FormattedSchedules 
where ScheduleName = @ScheduleName;

and the rowcount is greater than 0 so it is getting results. I do not understand what index is out of range or why the collection is 0 Code is below:

Tried .Rows.Add(1) and .Rows.Add() and .Rows.Add("")

    Dim FSchedCmd As SqlCommand
    Dim FSchedSQL As String
    Dim FSchedConn As New SqlConnection()
    Dim FSchedadapter As New SqlDataAdapter()
    Dim i As Integer = 0
    Dim rowIndex As Integer
    Dim row As DataGridViewRow

    AddedNewRow = 1

    Dim dsFSched As New DataSet()
    FSchedSQL = "Select ShiftName, ScheduleStart, ScheduleEnd, Position, ADP_ID1, Name1, ADP_ID2, Name2, ADP_ID3, Name3, ADP_ID4, Name4, ADP_ID5, Name5, ADP_ID6, Name6, ADP_ID7, Name7 from FormattedSchedules where ScheduleName = @ScheduleName;"
    Try
        If GlobalVariables.logProd = 1 Then
            GlobalVariables.strConnection = "CCAPProdConnectionString"
        Else
            GlobalVariables.strConnection = "CCAPTestConnectionString"
        End If
        FSchedConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings(GlobalVariables.strConnection).ConnectionString
        FSchedConn.Open()
        FSchedCmd = New SqlCommand(FSchedSQL, FSchedConn)
        FSchedCmd.Parameters.Add("@ScheduleName", SqlDbType.VarChar).Value = cboCreateScheduleName.Text
        FSchedadapter.SelectCommand = FSchedCmd
        FSchedadapter.Fill(dsFSched)
        FSchedadapter.Dispose()
        FSchedCmd.Dispose()
        FSchedConn.Close()
        'dgvCreateSchedule.DataSource = dsFSched.Tables(0)
        dgvCreateSchedule.Rows.Clear()
        With dgvCreateSchedule
            Dim RowNo As Long = 0
            '.RowCount = 0
            While RowNo <= dsFSched.Tables(0).Rows.Count - 1

                .Rows.Add(1)
                .Rows(RowNo).Cells(0).Value = dsFSched.Tables(0).Rows(RowNo).Item(0) 'ShiftName
                '.Rows(RowNo).Cells(1).Value = dsFSched.Tables(0).Rows(RowNo).Item(1) 'Start Time
                .Rows(RowNo).Cells(1).Value = Convert.ToDateTime(dsFSched.Tables(0).Rows(RowNo).Item(1)).TimeOfDay
                '.Rows(RowNo).Cells(2).Value = dsFSched.Tables(0).Rows(RowNo).Item(2) 'End Time
                .Rows(RowNo).Cells(2).Value = Convert.ToDateTime(dsFSched.Tables(0).Rows(RowNo).Item(2)).TimeOfDay 'End Time
                .Rows(RowNo).Cells(3).Value = dsFSched.Tables(0).Rows(RowNo).Item(3) 'Position
                .Rows(RowNo).Cells(4).Value = dsFSched.Tables(0).Rows(RowNo).Item(4) 'ADP_ID1
                .Rows(RowNo).Cells(5).Value = dsFSched.Tables(0).Rows(RowNo).Item(5) 'Name1
                .Rows(RowNo).Cells(6).Value = dsFSched.Tables(0).Rows(RowNo).Item(6) 'ADP_ID2
                .Rows(RowNo).Cells(7).Value = dsFSched.Tables(0).Rows(RowNo).Item(7) 'Name2
                .Rows(RowNo).Cells(8).Value = dsFSched.Tables(0).Rows(RowNo).Item(8) 'ADP_ID3
                .Rows(RowNo).Cells(9).Value = dsFSched.Tables(0).Rows(RowNo).Item(9) 'Name3
                .Rows(RowNo).Cells(10).Value = dsFSched.Tables(0).Rows(RowNo).Item(10) 'ADP_ID4
                .Rows(RowNo).Cells(11).Value = dsFSched.Tables(0).Rows(RowNo).Item(11) 'Name4
                .Rows(RowNo).Cells(12).Value = dsFSched.Tables(0).Rows(RowNo).Item(12) 'ADP_ID5
                .Rows(RowNo).Cells(13).Value = dsFSched.Tables(0).Rows(RowNo).Item(13) 'Name5
                .Rows(RowNo).Cells(14).Value = dsFSched.Tables(0).Rows(RowNo).Item(14) 'ADP_ID6
                .Rows(RowNo).Cells(15).Value = dsFSched.Tables(0).Rows(RowNo).Item(15) 'Name6
                .Rows(RowNo).Cells(16).Value = dsFSched.Tables(0).Rows(RowNo).Item(16) 'ADP_ID7
                .Rows(RowNo).Cells(17).Value = dsFSched.Tables(0).Rows(RowNo).Item(17) 'Name7
                RowNo = RowNo + 1
            End While
        End With

        If dgvCreateSchedule.RowCount > 0 Then
            dgvCreateSchedule.Rows(0).Selected = True
            dgvCreateSchedule.CurrentCell = dgvCreateSchedule.Rows(0).Cells(0)
            'dgvCreateSchedule.FirstDisplayedScrollingRowIndex = dgvCreateSchedule.CurrentRow.Index
        End If
    Catch ex As Exception
        MessageBox.Show("Cannot open FormattedSchedules to load grid")
    End Try
    AddedNewRow = 0

Error message from line: .Rows.Add(1)

Index was out of range. Must be non-negative and less than the size of the collection." & vbCrLf & "Parameter name: index

This should be the fastest option:

dgvCreateSchedule.Rows.Clear()
For Each xrow As DataRow In TempDataTable.dsFSched.Tables(0).Rows
            dgvCreateSchedule.Rows.Add(xrow.ItemArray)
Next

What it does adds all "Cells" along with row.

And when editing cells, I prefer to use

dgvCreateSchedule(y,x).Value = somevalue 
'Though it's a little bit strange, as it's column first then row for location hence y then x axis , opposed to usual row then column thats x then y axis

假设有相同的列数/顺序,则以这种方式添加

.Rows.Add(dsFSched.Tables(0).Rows(RowNo).ItemArray)

I changed the name of the DGV to DataGridView1 because that is what I happened to have in my test project.

You can use conditional compile statements to chose the correct connection string. Not necessary to keep a Boolean variable somewhere to determine correct string. I know I would forget to change it for the release version.

You did a good job closing and disposing of database objects but if there is an error all that good work will be for naught. A Using...End Using block will accomplish the close, dispose even if there is an error.

Pass the connection string directly to the constructor of the connection and pass the Sql statement and the connection directly to the constructor of the command.

Don't open your connection until the last minute. In the case of a DataAdapter.Fill , the connection is opened and closed for you however, if the adapter finds and open connection it leaves it open. In this case there is no need for an adapter or a DataSet .

I do not see anything wrong with your line .Rows.Add(1) . The problem comes on the next line. The index of DataGridView.Rows is an Int32 , Integer in vb.net, and you have declared RowNo as Long . Of course you will want to use the code suggested by @CruleD answer.

Private Sub OPCode()
    Dim dt As New DataTable
    Dim FSchedSQL = "Select ShiftName, ScheduleStart, ScheduleEnd, Position, ADP_ID1, Name1, ADP_ID2, Name2, ADP_ID3, Name3, ADP_ID4, Name4, ADP_ID5, Name5, ADP_ID6, Name6, ADP_ID7, Name7 from FormattedSchedules where ScheduleName = @ScheduleName;"
    Try
#If Not DEBUG Then
        GlobalVariables.strConnection = "CCAPProdConnectionString"
#Else
        GlobalVariables.strConnection = "CCAPTestConnectionString"
#End If
        Using FSchedConn As New SqlConnection(ConfigurationManager.ConnectionStrings(GlobalVariables.strConnection).ConnectionString)
            Using FSchedCmd As New SqlCommand(FSchedSQL, FSchedConn)
                FSchedCmd.Parameters.Add("@ScheduleName", SqlDbType.VarChar).Value = cboCreateScheduleName.Text
                FSchedConn.Open()
                dt.Load(FSchedCmd.ExecuteReader)
            End Using
        End Using
        DataGridView1.Rows.Clear()
        For Each xrow As DataRow In dt.Rows
            DataGridView1.Rows.Add(xrow.ItemArray)
        Next
        If DataGridView1.RowCount > 0 Then
            DataGridView1.Rows(0).Selected = True
            DataGridView1.CurrentCell = DataGridView1.Rows(0).Cells(0)
        End If
    Catch ex As Exception
        MessageBox.Show("Error loading grid")
    End Try
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM