kwi/100
[C#] Row select on right click (context menu)
When using DataGridView control, activating it’s context menu (by right click on the grid) will not select the row/cell you are clicking at. For most of the operations users right-clicking on the grid want to perform operation on that selected item.
Solution to this problem is to select item at same time as the Context menu is shown by using Opening event of the context menu. Following code should be pasted into the Opening event handler function:
Point p = _myGRID.PointToClient(Cursor.Position);
DataGridView.HitTestInfo hti = _myGRID.HitTest(p.X, p.Y);
if (hti.RowIndex > -1)
{
_grid_Feeds.ClearSelection();
_grid_Feeds.Rows[hti.RowIndex].Selected = true;
}
The right clicked row will be selected and from now on you can get the bound object by _myGRID.SelectedRow .
sty/100
[C#] Easy solution for AutoScroll in GridView
Poking around standard WinForms GridView control I found it have not any „Autoscroll” properties. A proper approach would be create new control inherited from base GridView with altered component drawing and focusing etc, but I didn’t have time and will to do this, especially for my extremally simple FileSorter tool. So I came up with easy solution.
The Problem:
Application have a grid, which is in real time adding new rows. When it’s view area height is reached, more rows are showed hidden „below” the view area of grid, and user is forced to use vertical scroll bar to scroll to them.
Solution:
We can use „FirstDisplayCell” property of DataGridView property
Code:
if(_grid.Rows.Count>0 && _grid.Rows[_grid.Rows.Count-1].Cells.Count>0) _grid.FirstDisplayedCell = _grid.Rows[_grid.Rows.Count-1].Cells[0];
Solution in 2 lines of code
Additional Notes:
Method is thread safe and updates GUI properly using Invoke while invoking on a _grid object
lis/090
[.NET] Showing menu on button click
This extremally easy thing, sometimes makes so much problem for someone who don’t know how to use .NET build in functions. As I saw, similar problem implementation in six lines of code (with pretty much calculations) it’s can be easily achived in one line.
Problem: we want to show menu, on center of a button, which was clicked.
Graphic representation:

Solution:
_context_menu.Show(_button_myButton, new Point(_button_myButton.Width/2, _button_myButton.Height/2));