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
-
Mouse Down
- Current Cell Changed
- 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.
jaskaran singhPosted Sep 19, 2011, 10:02 PM
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