Many times you want to select multiple columns in a DataGrid and highlight the columns selected.
In the DataGrid MouseDown Event you will find out if you have selected a column header through the hit test. You then find the co-ordinate of the column and construct a rectangle out of that. If you are selecting multiple columns you can store the index of the columns and the rectangle in ArrayList.
Make sure you clear the ArrayList when you HitType is None.
protected void dataGrid1_MouseDown (object sender, System.Windows.Forms.MouseEventArgs e)
{
m_HitTest = dataGrid1.HitTest(e.X,e.Y);
if ( m_HitTest.Type == DataGrid.HitTestType.ColumnHeader )
{
int xCoordinate = this.GetLeftmostColumnHeaderXCoordinate( m_HitTest.Column );
int yCoordinate = this.GetTopmostColumnHeaderYCoordinate( e.X, e.Y );
int columnWidth = dataGrid1.TableStyles[0].GridColumnStyles
m_HitTest.Column].Width;
int columnHeight = this.GetColumnHeight( yCoordinate );
columnRegion = new Rectangle( xCoordinate, yCoordinate, columnWidth, columnHeight );
m_RectangleOfSelectedColumns.Add(columnRegion);
m_IndexOfSelectedColumns.Add(m_HitTest.Column);
}
else if(m_HitTest.Type == DataGrid.HitTestType.None)
{
this.m_RectangleOfSelectedColumns.Clear();
m_IndexOfSelectedColumns.Clear();
this.dataGrid1.Refresh();
}
}
In the DataGrid paint method you just fill the rectangles you contructed before in MouseDown Event.
private void dataGrid1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
if (m_HitTest != null && m_HitTest.Type == DataGrid.HitTestType.ColumnHeader )
{
for (int i = 0; i < this.m_RectangleOfSelectedColumns.Count; i++)
{
Rectangle columnRegion = (Rectangle)m_RectangleOfSelectedColumns[i];
SolidBrush blackBrush = new SolidBrush( Color.FromArgb( 255, 0, 0, 0 ) );
SolidBrush darkGreyBrush = new SolidBrush( Color.FromArgb( 100, 229, 229, 229 ) );
Pen blackPen = new Pen( blackBrush, 1F );
g.FillRectangle( darkGreyBrush, columnRegion);
g.DrawRectangle( blackPen, columnRegion );
}
}
}
You will get result like below.
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.
waqar laghariPosted Mar 27, 2009, 7:45 AM
Hello, This is best artical i have ever seen. this artical solved my problem. i would like to thank you brother. Best regards Waqar Hussain Laghari