error in get data from access database to datagrid

2020-05-01 04:52发布

问题:

i have a problem when i click to item in datagridview to get more information ! ok ? my code :

Try
        If (DataGridView1.Rows.Count = 0) Then Return
        TextBox1.Text = String.Empty
        TextBox2.Text = String.Empty
        TextBox3.Text = String.Empty
        TextBox4.Text = String.Empty
        Dim id As String = DataGridView1(2, DataGridView1.SelectedRows(0).Index).Value
        Dim dt As DataTable = New DBConnect().selectdata(String.Format("SELECT items.ClientName, items.ClientAddress, items.ClientPhone, items.ClientCredit, items.ClientLastPay FROM items where items.ClientID = {0}", id))
        TextBox1.Text = dt.Rows(0)(0).ToString
        TextBox2.Text = dt.Rows(0)(1).ToString
        TextBox3.Text = dt.Rows(0)(2).ToString
        TextBox4.Text = dt.Rows(0)(3).ToString
        dt.Dispose()
        dt = Nothing
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

by debugging the error is in this line :

Dim id As String = DataGridView1(2, DataGridView1.SelectedRows(0).Index).Value.ToString

thats my full source code http://up.dev-point.com/download279606.html

回答1:

You are trying to access the DataGridView like an array, when you need to specify that you're looking in the rows and columns. Instead of

DataGridView1(2, DataGridView1.SelectedRows(0).Index).Value

you can write

DataGridView1.Columns(2).Cells(DataGridView1.SelectedRows(0).Index).Value

However, relying on SelectedRows is not the best way to do it. What if the user accidentally selected a few rows and clicked the bottom one?

Assuming your code is in a CellClick handler with

(sender As Object, e As DataGridViewCellEventArgs)

you should use the DataGridViewCellEventArgs to tell what row you're on instead of relying on SelectedRows:

Dim id As String = DataGridView1(e.RowIndex).Cells(2).Value