How to get the value of a cell in a DataGridViewCo

2020-05-07 18:42发布

问题:

I have a simple datagridview with a DataGridViewComboBoxColumn, and a DataGridViewTextBoxColumn. The Combobox is populated as follows: (where PNcombo.text is a standard combobox)

  Dim objConn As New SqlConnection(DatabaseConnection.FISSQLConnectionString)
    Dim str1 As New StringBuilder
    str1.Append("SELECT cp.Description, cp.CollectionPointId ")
    str1.Append("FROM CollectionPoints cp INNER JOIN ")
    str1.Append("   Products p ON cp.ProductIdValue = p.ProductId ")
    str1.Append("WHERE p.PartNumber = N'" & Trim(PNcombo.Text) & "'")
    Dim objCommand As SqlCommand = New SqlCommand(str1.ToString, objConn)
    objConn.Open()
    Dim dt As New DataTable
    dt.Load(objCommand.ExecuteReader)

   Dim colDesription As New DataGridViewComboBoxColumn
    With colDesription
        .DataSource = dt
        .DisplayMember = "Description"
        .ValueMember = "Description"
    End With
    Me.DataGridView1.Columns.Add(colDesription)

  Dim colCollectionPoint As New DataGridViewTextBoxColumn
    With colCollectionPoint
        .Name = "CollectioPntId"
        .DataPropertyName = "CollectionPointId"
    End With
    DataGridView1.Columns.Add(colCollectionPoint)

The combox in the dgv populates correctly, but I need to get the associated "CollectionPointID" and put it in the textbox within the dgv.

From here I don't know how to get the cell value that I select from the combobox.

回答1:

I usually reference the .Value property of the cell, but you'll need to cast it to the correct type (i.e. String in your example) because .Value is of type Object:

DirectCast(DataGridView1.SelectedRows(0).Cells("Description").Value, String) or

CStr(DataGridView1.SelectedRows(0).Cells("Description").Value)