[英]How to limit number of rows that can be selected in DataGridView
I have got a DataGridView with a MultiSelect=True in C#. 我在C#中有一个MultiSelect = True的DataGridView 。
I want to limit the maximum number of simultaneously selected rows to 2, so that user can select only one or two rows at the same time. 我想将同时选择的行的最大数量限制为2,以便用户只能同时选择一或两行。 How can I achive this? 我该如何实现?
There are no events like BeforeSelectedRowsChanged or ValidatingSelectedRows. 没有像BeforeSelectedRowsChanged或ValidatingSelectedRows这样的事件。
My DataGridView is Readonly also. 我的DataGridView也为只读。
** EDIT ** my SelectionMode is FullRowSelect **编辑**我的SelectionMode是FullRowSelect
On the SelectionChanged event you can do this: 在SelectionChanged事件上,您可以执行以下操作:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedCells.Count > 2)
{
dataGridView1.SelectedCells[0].Selected = false;
}
}
This will prevent/undo selecting any more cells after selecting two. 选择两个后,这将防止/取消选择更多的单元格。
For whole rows: 对于整行:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 2)
{
dataGridView1.SelectedRows[0].Selected = false;
}
}
You could try overriding SetSelectedRowCore, calling the base with adding your new limitation to the selected condition. 您可以尝试覆盖SetSelectedRowCore,通过将新限制添加到所选条件来调用基础。
protected virtual void SetSelectedRowCore(int rowIndex,bool selected )
{
base(rowIndex, selected && currentSelection < allowedSelectionCount);
}
This always leave selected 2 last selected rows 这总是保留选中的2个最后选择的行
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 2)
{
for (int i = 2; i < dataGridView1.SelectedRows.Count; i++)
{
dataGridView1.SelectedRows[i].Selected = false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.