Right click in datagridview

compguru910

Well-known member
Joined
Nov 25, 2009
Messages
47
Programming Experience
3-5
This is probably simple, but how do you make it so that when you right click a cell in a datagridview, it changes the selection? I want to make it so that if I right click it brings up a menu that directly relates to that cell. Thanks in advanced.

Plus, is there a way to run a query on a data table? I googled it, but only found ways to populate datatables with queries.
 
This is probably simple, but how do you make it so that when you right click a cell in a datagridview, it changes the selection? I want to make it so that if I right click it brings up a menu that directly relates to that cell.
Handle the CellMouseClick event of your grid. You can then get information about the cell, mouse button and mouse position to allow you to display a ContextMenuStrip on a right-click. You can store the cell in a variable and then access it again in the Click event handlers of your mneu items.
Plus, is there a way to run a query on a data table? I googled it, but only found ways to populate datatables with queries.
There are various ways depending on exactly what you want to achieve. You have the Select and Compute methods of the DataTable itself. You can also use the Sort and Filter methods of its DefaultView, or create your own DataView. Assuming .NET 3.5 or later, if you need something more advanced you can use LINQ to DataSet, e.g.
VB.NET:
Dim specialCustomerNames = From row In myDataTable.AsEnumerable() _
                           Where row.Field(Of Decimal)("TotalPurchases") > 10000D _
                           Select row.Field(Of String)("FirstName") & " " & row.Field(Of String)("LastName")
That code will return an enumerable list of names of customers who've spent more than $10,000.

In future, please ask unrelated questions in separate threads. One thread per topic and one topic per thread please.
 
I imagined it would have something to do with the mouse event, but how do I make it detect the right mouse button, and select the cell that its over? Im fairly new to this, so I really appreciate all the help you are providing
 
As with all event handlers, the 'e' parameter provides the event data. Check out the 'e' parameter for the CellMouseClick event and see what information it provides.
 
Back
Top