Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting Data from a datagrid

Status
Not open for further replies.

graydon123

Technical User
Feb 25, 2004
10
US
Here is a problme that I am having a hard time researching...

I have a datagrid that is bound to a database. The datagrid will display an employee's job history (data from the "Job Code" table). In the datagrid I only display a job start date and a job end date. I want the user to be able to double click on any row in the datagrid that would open up another form showing populated textboxes of the whole data row so the user can edit record.

Is this possible?

Thank you very much for your help!



 
When you double click a grid cell, the grid only gets the first click and the text box of the cell gets the second click - this prevents the double click event of the grid from firing. To prevent the text boxes from taking the second click, you need to remove them from the datagrid control collection (but leave any scrollbars!).

The first code snippet is from
Code:
Dim ar As ArrayList = New ArrayList

For Each ct As Control In DataGrid1.Controls

    If TypeOf ct Is HScrollBar OrElse TypeOf ct Is VScrollBar Then ar.Add(ct)

Next

DataGrid1.Controls.Clear()

DataGrid1.Controls.AddRange(CType(ar.ToArray(GetType(Control)), Control()))
You can then catch the double click by handling the grid event:
Code:
Private Sub DataGrid1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGrid1.DoubleClick

    Dim pt As Point = Cursor.Position

    Dim hti As DataGrid.HitTestInfo = DataGrid1.HitTest(pt.X, pt.Y)

    Dim bm As BindingManagerBase = DataGrid1.BindingContext(DataGrid1.DataSource)

    Dim dr As DataRow = CType(bm.Current, DataRowView).Row

    MessageBox.Show(dr(0).ToString())

End Sub
Using the BindingManagerBase ensures that we get the correct row returned. HitTestInfo also exposes a row property, but that is the row number of the grid, not necessarily the row number of the underlying datasource if the datasource has been sorted.

I have displayed the first column value in a message box, but obviously now you have the row you can do whatever you need to.
 
Thanks Sheldon I appreciate your help with this. I am getting a syntax error and a "ct" not declared from the 2nd line of the code from Do you happen to know why?
 
The syntax I have shown is version 1.1 of the framework.

For version 1.0, change it to:
Code:
Dim ct As Control

For Each ct In DataGrid1.Controls
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top