C# DataGridView 禁止启动时自动选中内容
C# DataGridView 禁止启动时自动选中内容
在 Windows Forms 应用程序中使用 DataGridView 控件时,您可能希望控制其默认选中行为。默认情况下,DataGridView 在启动时可能会自动选中第一行。如果您需要禁止此行为,可以通过设置 SelectionMode 和 ClearSelection 属性来实现。
代码示例
以下 C# 代码示例演示了如何设置 DataGridView 在启动时不自动选中行:csharpusing System;using System.Windows.Forms;
class Program{ static void Main(string[] args) { // 创建一个窗口 Form form = new Form();
// 创建一个 DataGridView 控件 DataGridView dataGridView = new DataGridView(); dataGridView.Dock = DockStyle.Fill;
// 创建列 dataGridView.Columns.Add('Name', 'Name'); dataGridView.Columns.Add('Age', 'Age'); dataGridView.Columns.Add('City', 'City');
// 添加行并赋值 dataGridView.Rows.Add('John', 25, 'New York'); dataGridView.Rows.Add('Alice', 30, 'London'); dataGridView.Rows.Add('Bob', 35, 'Paris');
// 设置选中模式为 FullRowSelect dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
// 清除当前选中的行 dataGridView.ClearSelection();
// 将 DataGridView 添加到窗口中 form.Controls.Add(dataGridView);
// 显示窗口 Application.Run(form); }}
代码解释
-
设置 SelectionMode 属性:
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;- 此行代码将 DataGridView 的选择模式设置为FullRowSelect,这意味着用户可以选择整行。您可以根据需要选择其他选择模式。 -
清除当前选择:
dataGridView.ClearSelection();- 此行代码使用ClearSelection方法清除 DataGridView 中的任何当前选择。这确保了在启动时不会选中任何行。
通过结合使用 SelectionMode 和 ClearSelection,您可以轻松地控制 DataGridView 的默认选中行为,并根据需要自定义用户体验。
原文地址: https://www.cveoy.top/t/topic/The 著作权归作者所有。请勿转载和采集!