Showing posts with label ctrl key. Show all posts
Showing posts with label ctrl key. Show all posts

Friday, 16 February 2007

DataGridView multiselect without CTRL

One of my mates has asked my about how to enable a datagridview multiselection without pressing CTRL key (for a touch screen). I haven't tested it throughly, but here comes a (C#) possible solution:

I´ve tested it only with a Datagridview configured for full row selection.

Basically I hold a private collection of the rows I want to select and every time a row is pressed, it´s selected or removed accordingly

The empty override method avoids selection refresh. Try to remove it and see...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;

namespace MyDataGridView
{
public partial class MyDataGridV : DataGridView
{
private Hashtable mySelectedRows = new Hashtable();

public MyDataGridV()
{

}

protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
{

}

protected override void OnCellClick(DataGridViewCellEventArgs e)
{
if (mySelectedRows.ContainsKey(e.RowIndex))
{
mySelectedRows.Remove(e.RowIndex);
}
else
{
mySelectedRows.Add(e.RowIndex, this.Rows[e.RowIndex]);
}
for (int i = 0; i < this.Rows.Count; i++)
{
if (mySelectedRows.Contains(i))
{
this.SetSelectedRowCore(i, true);
}
else
{
this.SetSelectedRowCore(i, false);
}
}
Debug.Assert(this.SelectedRows.Count == mySelectedRows.Count, "Selected rows number don´t match");
base.OnCellClick(e);
}


}
}