ARTICLE

Multi Selection of DataGrid Rows without Ctrl Click

Posted by suparba Panda Articles | Windows Forms C# July 31, 2005
This article shows how to select multiple rows in a DataGrid without using CRTL.
Reader Level:

The DataGrid have a default behavior of multi-selecting rows if you press the Ctrl key and select. You can change that to a single click and still select multiple rows.

 

For that you have to address three event handlers. The order of events in a .net Page is

  1. Mouse Down
  2. Current Cell Changed
  3. Click Mouse Up

This is what you write in the Event. And you create an array list to store the values of which row is selected. Because sometimes highlighted row may not be considered as the selected row or selected row may not be highlighted.

 

Source code:  

ArrayList selectedRow = new ArrayList();
private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
{
int c = dataGrid1.CurrentRowIndex;
dataGrid1.Select(c);
Console.WriteLine("In Cell Changed");
dataGrid1_Click( sender, e);
}
private void dataGrid1_Click(object sender, EventArgs e)
{
int c = dataGrid1.CurrentRowIndex;
dataGrid1.Select(c);
Console.WriteLine("In Click");
}
private void dataGrid1_MouseUp(object sender, MouseEventArgs e)
{
int c = dataGrid1.CurrentRowIndex;
if(selectedRow.Contains(c))
{
dataGrid1.UnSelect(c);
selectedRow.Remove(c);
}
else
{
dataGrid1.Select(c);
selectedRow.Add(c);
}
for (int i = 0; i < selectedRow.Count; i++)
{
dataGrid1.Select(
int.Parse(selectedRow[i].ToString()));
}
Console.WriteLine("In Mouse Up");
}

See the attached source code for more details.

Login to add your contents and source code to this article
post comment
     

Hi, Good work !! Your code works perfect and the selection mechanism is exactly what i was looking for but the rows flickering is kinda annoying, is there any way we can make it look better ?? Datagrid/Datagridview doesn't offer BeginUpdate/EndUpdate methods, is there any way we can avoid the redrawing of rows if its already selected ? Thanks Jaskaran

Posted by jaskaran singh Sep 19, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter