使用dataGridView3.ClearSelection();没有效果
时间: 2023-06-18 19:02:21 浏览: 60
`ClearSelection()` 方法只是清除了单元格的选中状态,但是并没有清除掉行或者列的选中状态。如果你想要清除行或者列的选中状态,可以使用以下的代码:
```csharp
dataGridView3.CurrentCell = null; // 将当前单元格设为 null,以便清除行或列的选中状态
dataGridView3.ClearSelection(); // 清除单元格的选中状态
```
此外,你还可以通过以下代码清除行的选中状态:
```csharp
dataGridView3.Rows.Cast<DataGridViewRow>().ToList().ForEach(x => x.Selected = false);
```
或者通过以下代码清除列的选中状态:
```csharp
dataGridView3.Columns.Cast<DataGridViewColumn>().ToList().ForEach(x => x.Selected = false);
```
希望对你有所帮助。
相关问题
c# datagridview右键菜单
以下是C#实现DataGridView选中一行右键出现菜单的示例代码:
```csharp
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var hti = dataGridView1.HitTest(e.X, e.Y);
dataGridView1.ClearSelection();
dataGridView1.Rows[hti.RowIndex].Selected = true;
ContextMenuStrip m = new ContextMenuStrip();
m.Items.Add("菜单项1");
m.Items.Add("菜单项2");
m.Items.Add("菜单项3");
m.Show(dataGridView1, new Point(e.X, e.Y));
}
}
```
以上代码中,我们通过`MouseClick`事件来监听鼠标右键点击事件,然后通过`HitTest`方法获取鼠标点击的位置,进而选中该行数据,并在该行位置弹出菜单。
datagridview取消默认选中的方法
要取消 DataGridView 控件中默认选中行的方法,您可以通过设置 DataGridView 控件的 `CurrentCell` 属性为 `null` 值来实现。可以在 DataGridView 控件的事件中添加以下代码:
```csharp
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
dataGridView1.CurrentCell = null;
}
}
```
这样在每次 DataGridView 绑定数据完成后,就会取消默认的选中行。
另外,如果您希望在初始化 DataGridView 控件时就取消默认选中行,可以在构造函数中添加以下代码:
```csharp
public Form1()
{
InitializeComponent();
dataGridView1.RowsAdded += DataGridView1_RowsAdded;
}
private void DataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
dataGridView1.ClearSelection();
}
}
```
这样在 DataGridView 添加行时,就会自动取消默认选中行。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)