从访问数据库获取数据到datagridview Vb.Net时出错
当我点击datagridview中的项目以获取更多信息时,我遇到了问题! 好 ? 我的代码:
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
通过调试错误是在这一行:
Dim id As String = DataGridView1(2, DataGridView1.SelectedRows(0).Index).Value.ToString
这是我的完整源代码http://up.dev-point.com/download279606.html
当您需要指定要查看行和列时,您尝试像数组一样访问DataGridView。 代替
DataGridView1(2, DataGridView1.SelectedRows(0).Index).Value
你可以写
DataGridView1.Columns(2).Cells(DataGridView1.SelectedRows(0).Index).Value
但是,依赖SelectedRows并不是最好的方法。 如果用户意外选择了几行并点击了底行,该怎么办?
假设你的代码在CellClick处理程序中
(sender As Object, e As DataGridViewCellEventArgs)
您应该使用DataGridViewCellEventArgs来告诉您所在的行而不是依赖于SelectedRows:
Dim id As String = DataGridView1(e.RowIndex).Cells(2).Value