不按控制键选择多行 [英] Select multiple Rows without pressing Control Key
问题描述
我有一个 gridview,我可以通过按控制键来选择多行.是否可以在不按控制键的情况下实现相同的效果.
I have a gridview where I can select multiple rows by pressing a control key. Is it possible to achieve the same without pressing a control key.
推荐答案
由于 .net 默认操作也会更新 datagridview
的 slectedrows
,因此您需要有一个保留旧选择的数组:
As the .net default action will also update the slectedrows
of your datagridview
you need to have an array to reserve the old selections:
DataGridViewRow[] old;
将在 CellMouseDown
更新(在默认 .net 操作修改您的选择之前):
which will be updated at CellMouseDown
(before the default .net action modify your selections):
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
old = new DataGridViewRow[dataGridView1.SelectedRows.Count];
dataGridView1.SelectedRows.CopyTo(old,0);
}
之后,您可以在 RowHeaderMouseClick
中进行更改(因为 RowHeaderSelect
是默认的 datagridview selectionmode
)或使用 CellMouseClick
用于 FullRowSelect
并重新选择那些旧的选定行:
after that, you can do your changes in RowHeaderMouseClick
(as RowHeaderSelect
is the default datagridview selectionmode
) or use CellMouseClick
for FullRowSelect
and reselect those old selected rows:
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewRow gr in old)
{
if (gr == dataGridView1.CurrentRow)
{
gr.Selected = false;
}
else
{
gr.Selected = true;
}
}
}
更好的解决方案:
您需要实现自己的 datagridview
派生自原始代码并覆盖 OnCellMouseDown
&OnCellMouseClick
以取消默认取消选择操作并使其平滑.像这样创建一个新类:
Better solution:
You need to implement your own datagridview
derived from the original one and override OnCellMouseDown
&OnCellMouseClick
to cancel the default deselect action and make it smooth. make a new Class as something like this:
Using System;
Using System.Windows.Forms;
public class myDataGridView:DataGridView
{
protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
{
//base.OnCellMouseDown(e);
this.Rows[e.RowIndex].Selected = !this.Rows[e.RowIndex].Selected;
}
protected override void OnCellMouseClick(DataGridViewCellMouseEventArgs e)
{
//base.OnCellMouseClick(e);
}
}
并在您的 Form.Designer.cs 中将 DataGridView
对象 datagridview1
(如果这是名称)更改为 myDataGridView
对象......
and in your Form.Designer.cs change DataGridView
object datagridview1
(if that is the name) to myDataGridView
object......
例如:更改
私有 System.Windows.Forms.DataGridView dataGridView1;
to
private myDataGridView dataGridView1;
和改变
this.dataGridView1=new System.Windows.Forms.DataGridView()
到
this.dataGridView1=new myDataGridView ()
这篇关于不按控制键选择多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!