Tepken Vannkorn
Tepken Vannkorn

Reputation: 9713

Double Clicking on any DataGridView row in VB.NET to display the result in the form controls

I didn't get the result I want from the following code:

    Private Sub tblView_SelectionChanged(ByVal sender As System.oject, ByVal e as System.EventArgs)Handles tblView.SelectionChanged
        Dim st As String = tblView.SelectedRows.ToString
        txtID.Text = st(0)
        Try
           myCommand = New SqlCommand("SELECT * FROM tblRack WHERE RackID = "& txtID.Text &"", myConnection)
           myReader = myCommand.ExecuteReader()
           While myReader.Read
               txtID.Text = myReader(0).ToString
               txtRack.Text = myReader(1).ToString
           End While
           myReader.Close()
        Catch ex As Exception
           MsgBox (ex.Message)
        End Try
 End Sub

I wanted the data I selected on the datagridview row to be display in the textbox, but it displays the error message that st(0) produces "S" which is incompatible to my RackID data type. Any idea?

Upvotes: 0

Views: 8180

Answers (2)

Kelvink78
Kelvink78

Reputation: 11

Try this

txtID.text = myReader.Item(0)
txtRack.text = myReader.Item(1)

or

txtID.text = myReader.Item("Fieldname1")
txtRack.text = myReader.Item("Fieldname2")

Upvotes: 1

Edwin de Koning
Edwin de Koning

Reputation: 14387

You are converting the SelectdRows object to a string, which will probably return something like "System.Windows.Forms.DataGridViewSelectedRowCollection". Doing st(0) will take first charachter from this string, which is an 'S'.

Perhaps you should try this:

    Dim st As String = tblView.SelectedRows[0].Cells[0].Value.ToString
    txtID.Text = st

Upvotes: 2

Related Questions