syncfusion-winforms-datagrid
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion WinForms DataGrid
实现Syncfusion WinForms DataGrid
A comprehensive guide for implementing the Syncfusion Windows Forms DataGrid (SfDataGrid) component, a powerful control for displaying and manipulating tabular data with features like columns, filtering, sorting, grouping, editing, summaries, and export capabilities.
本文是一份关于实现Syncfusion Windows Forms DataGrid(SfDataGrid)组件的综合指南,该组件是一款高性能控件,用于显示和操作表格数据,具备列管理、筛选、排序、分组、编辑、汇总和导出等功能。
When to Use This Skill
何时使用本技能
Use this skill when you need to:
- Display tabular data in Windows Forms applications
- Define and customize columns (text, numeric, date, checkbox, combobox, etc.)
- Implement data operations like filtering, sorting, and grouping
- Enable in-grid editing with validation
- Display data summaries and aggregations
- Implement selection functionality (single, multiple, row, cell)
- Export grid data to Excel or PDF
- Apply conditional styling based on data values
- Create master-detail views with hierarchical data
- Enable drag-and-drop operations in grids
- Localize grid text and messages
- Serialize and deserialize grid state
当你需要以下功能时,可以使用本技能:
- 在Windows Forms应用程序中显示表格数据
- 定义和自定义列(文本、数值、日期、复选框、下拉框等)
- 实现筛选、排序和分组等数据操作
- 启用带验证的网格内编辑
- 显示数据汇总和聚合信息
- 实现选择功能(单选、多选、行选择、单元格选择)
- 将网格数据导出到Excel或PDF
- 根据数据值应用条件样式
- 使用分层数据创建主从视图
- 在网格中启用拖放操作
- 本地化网格文本和消息
- 序列化和反序列化网格状态
Component Overview
组件概述
The Syncfusion WinForms DataGrid (SfDataGrid) is a high-performance data grid control that provides:
- Column Management: Auto-generation, manual definition, stacked headers, column types
- Data Operations: Filtering (Excel-like UI), sorting, grouping with expand/collapse
- Editing: In-grid editing with various modes and validation
- Summaries: Group summaries, table summaries, caption summaries
- Selection: Row, cell, or any selection with multiple modes
- Export: Excel and PDF export with customization
- Styling: Conditional styling, custom cell rendering
- Advanced: Master-detail views, drag-drop, localization, serialization
Syncfusion WinForms DataGrid(SfDataGrid)是一款高性能数据网格控件,提供以下功能:
- 列管理:自动生成、手动定义、堆叠表头、列类型
- 数据操作:筛选(类Excel UI)、排序、带展开/折叠的分组
- 编辑:多种模式的网格内编辑及验证
- 汇总:组汇总、表格汇总、标题汇总
- 选择:行、单元格或任意选择,支持多种模式
- 导出:可自定义的Excel和PDF导出
- 样式:条件样式、自定义单元格渲染
- 高级功能:主从视图、拖放、本地化、序列化
Getting Started
快速入门
Installing NuGet Packages
安装NuGet包
To use the SfDataGrid control in your WinForms application, you need to install the required NuGet packages. The primary package is , which automatically includes all necessary dependencies.
Syncfusion.SfDataGrid.WinForms要在WinForms应用中使用SfDataGrid控件,你需要安装所需的NuGet包。主要包为,它会自动包含所有必要的依赖项。
Syncfusion.SfDataGrid.WinFormsOption 1: Using NuGet Package Manager (Visual Studio)
选项1:使用Visual Studio的NuGet包管理器
- Right-click on your project in Solution Explorer
- Select "Manage NuGet Packages"
- Click on the Browse tab
- Search for
Syncfusion.SfDataGrid.WinForms - Select the package and click "Install"
- Accept the license agreement
- 在解决方案资源管理器中右键点击你的项目
- 选择**“管理NuGet程序包”**
- 点击**“浏览”**标签
- 搜索
Syncfusion.SfDataGrid.WinForms - 选择该包并点击**“安装”**
- 接受许可协议
Option 2: Using Package Manager Console
选项2:使用包管理器控制台
Open the Package Manager Console (Tools → NuGet Package Manager → Package Manager Console) and run:
powershell
Install-Package Syncfusion.SfDataGrid.WinForms打开包管理器控制台(工具 → NuGet包管理器 → 包管理器控制台)并运行:
powershell
Install-Package Syncfusion.SfDataGrid.WinFormsOption 3: Using .NET CLI
选项3:使用.NET CLI
For .NET Core/.NET 5+ projects, use the command line:
bash
dotnet add package Syncfusion.SfDataGrid.WinForms对于.NET Core/.NET 5+项目,使用命令行:
bash
dotnet add package Syncfusion.SfDataGrid.WinFormsOption 4: Manual packages.config (for .NET Framework)
选项4:手动配置packages.config(适用于.NET Framework)
For .NET Framework projects using packages.config, add this to your file:
packages.configxml
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Syncfusion.SfDataGrid.WinForms" version="27.1.57" targetFramework="net481" />
</packages>Then right-click the solution and select "Restore NuGet Packages".
Automatically Installed Dependencies:
Installing will automatically add these required dependencies:
Syncfusion.SfDataGrid.WinForms- Syncfusion.Data.WinForms
- Syncfusion.SfInput.WinForms
- Syncfusion.SfListView.WinForms
- Syncfusion.Grid.Windows
- Syncfusion.Shared.Base
- Syncfusion.Shared.Windows
- Syncfusion.Licensing
- Syncfusion.Compression.Base
For more information, see:
对于使用packages.config的.NET Framework项目,将以下内容添加到你的文件中:
packages.configxml
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Syncfusion.SfDataGrid.WinForms" version="27.1.57" targetFramework="net481" />
</packages>然后右键点击解决方案并选择**“还原NuGet包”**。
自动安装的依赖项:
安装会自动添加以下必要依赖项:
Syncfusion.SfDataGrid.WinForms- Syncfusion.Data.WinForms
- Syncfusion.SfInput.WinForms
- Syncfusion.SfListView.WinForms
- Syncfusion.Grid.Windows
- Syncfusion.Shared.Base
- Syncfusion.Shared.Windows
- Syncfusion.Licensing
- Syncfusion.Compression.Base
更多信息请参阅:
Adding Assembly References Manually
手动添加程序集引用
If you prefer to add assembly references manually without using NuGet:
- Right-click on your project in Solution Explorer
- Select "Add" → "Reference"
- Click "Browse" button
- Navigate to the Syncfusion installation folder:
- Default location:
C:\Program Files (x86)\Syncfusion\Essential Studio\Windows\<version>\Assemblies\4.0\
- Default location:
- Add the following required assemblies:
- Syncfusion.SfDataGrid.WinForms.dll (Core DataGrid control)
- Syncfusion.Data.WinForms.dll (Data operations)
- Syncfusion.SfInput.WinForms.dll (Input controls)
- Syncfusion.SfListView.WinForms.dll (List view support)
- Syncfusion.Grid.Windows.dll (Grid framework)
- Syncfusion.Shared.Base.dll (Shared utilities)
- Syncfusion.Shared.Windows.dll (Windows shared components)
- Syncfusion.Licensing.dll (License management)
- Click OK to add the references
如果你偏好不使用NuGet,而是手动添加程序集引用:
- 在解决方案资源管理器中右键点击你的项目
- 选择**“添加” → “引用”**
- 点击**“浏览”**按钮
- 导航到Syncfusion安装文件夹:
- 默认位置:
C:\Program Files (x86)\Syncfusion\Essential Studio\Windows\<version>\Assemblies\4.0\
- 默认位置:
- 添加以下必要的程序集:
- Syncfusion.SfDataGrid.WinForms.dll(核心DataGrid控件)
- Syncfusion.Data.WinForms.dll(数据操作)
- Syncfusion.SfInput.WinForms.dll(输入控件)
- Syncfusion.SfListView.WinForms.dll(列表视图支持)
- Syncfusion.Grid.Windows.dll(网格框架)
- Syncfusion.Shared.Base.dll(共享工具)
- Syncfusion.Shared.Windows.dll(Windows共享组件)
- Syncfusion.Licensing.dll(许可证管理)
- 点击**“确定”**添加引用
Registering Syncfusion License
注册Syncfusion许可证
Before using any Syncfusion control, you must register your license key. Add this code at the application entry point:
In Program.cs (recommended):
csharp
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
// Register Syncfusion license key BEFORE any Syncfusion control is created
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}Getting a License Key:
- Free Trial: Get a 30-day trial license from https://www.syncfusion.com/downloads
- Community License: Free for qualifying individuals and organizations
- Commercial License: For commercial use
在使用任何Syncfusion控件之前,你必须注册许可证密钥。在应用程序入口点添加以下代码:
在Program.cs中(推荐):
csharp
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
// 在创建任何Syncfusion控件之前注册Syncfusion许可证密钥
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}获取许可证密钥:
- 免费试用:从https://www.syncfusion.com/downloads获取30天试用许可证
- 社区许可证:符合条件的个人和组织可免费使用
- 商业许可证:用于商业用途
Creating the DataGrid Control
创建DataGrid控件
Method 1: Using Visual Studio Designer
方法1:使用Visual Studio设计器
- Open your form in the Visual Studio Designer
- Open the Toolbox (View → Toolbox or Ctrl+Alt+X)
- Locate "SfDataGrid" in the toolbox
- If not visible, ensure NuGet packages are installed and rebuild the project
- Look under Syncfusion Controls or All Windows Forms section
- Drag and drop the SfDataGrid onto your form
- The designer will automatically:
- Add the control to your form
- Add the required assembly references (if using designer for the first time)
- Generate the initialization code in the designer file
- 在Visual Studio设计器中打开你的窗体
- 打开工具箱(视图 → 工具箱 或 Ctrl+Alt+X)
- 在工具箱中找到**“SfDataGrid”**
- 如果不可见,请确保已安装NuGet包并重新生成项目
- 在Syncfusion控件或所有Windows Forms部分查找
- 拖放SfDataGrid到你的窗体上
- 设计器会自动:
- 将控件添加到窗体
- 添加所需的程序集引用(如果是首次使用设计器)
- 在设计器文件中生成初始化代码
Method 2: Adding the Control in Code
方法2:通过代码添加控件
Create the SfDataGrid control programmatically:
csharp
using System;
using System.Windows.Forms;
using Syncfusion.WinForms.DataGrid;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private SfDataGrid sfDataGrid1;
public Form1()
{
InitializeComponent();
// Create SfDataGrid instance
sfDataGrid1 = new SfDataGrid();
// Set position and size
sfDataGrid1.Location = new System.Drawing.Point(12, 12);
sfDataGrid1.Size = new System.Drawing.Size(760, 438);
// Or use Dock to fill the entire form
sfDataGrid1.Dock = DockStyle.Fill;
// Add to form's controls collection
this.Controls.Add(sfDataGrid1);
}
}
}以编程方式创建SfDataGrid控件:
csharp
using System;
using System.Windows.Forms;
using Syncfusion.WinForms.DataGrid;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private SfDataGrid sfDataGrid1;
public Form1()
{
InitializeComponent();
// 创建SfDataGrid实例
sfDataGrid1 = new SfDataGrid();
// 设置位置和大小
sfDataGrid1.Location = new System.Drawing.Point(12, 12);
sfDataGrid1.Size = new System.Drawing.Size(760, 438);
// 或者使用Dock填充整个窗体
sfDataGrid1.Dock = DockStyle.Fill;
// 添加到窗体的控件集合
this.Controls.Add(sfDataGrid1);
}
}
}Documentation and Navigation Guide
文档和导航指南
Column Management
列管理
📄 Read: references/columns.md
When you need to:
- Define columns (auto-generate vs manual definition)
- Work with different column types (GridTextColumn, GridNumericColumn, GridDateTimeColumn, GridCheckBoxColumn, GridComboBoxColumn, etc.)
- Customize auto-generated columns or use Data Annotations
- Add, remove, or reorder columns programmatically
- Create stacked headers spanning multiple columns
- Hide, show, or resize columns
- Enable column drag-and-drop for reordering
📄 阅读: references/columns.md
当你需要以下功能时:
- 定义列(自动生成vs手动定义)
- 使用不同的列类型(GridTextColumn、GridNumericColumn、GridDateTimeColumn、GridCheckBoxColumn、GridComboBoxColumn等)
- 自定义自动生成的列或使用数据注解
- 以编程方式添加、删除或重新排序列
- 创建跨多列的堆叠表头
- 隐藏、显示或调整列大小
- 启用列拖放以重新排序
Editing Data
数据编辑
📄 Read: references/editing.md
When you need to:
- Enable or disable editing for the grid or specific columns
- Configure edit modes (single-click, double-click, F2 key)
- Handle edit events (begin edit, end edit, value changed)
- Implement validation during editing
- Programmatically start, end, or cancel editing
- Customize cursor placement in edit mode
- Change cell values programmatically
📄 阅读: references/editing.md
当你需要以下功能时:
- 启用或禁用网格或特定列的编辑
- 配置编辑模式(单击、双击、F2键)
- 处理编辑事件(开始编辑、结束编辑、值更改)
- 在编辑期间实现验证
- 以编程方式启动、结束或取消编辑
- 自定义编辑模式下的光标位置
- 以编程方式更改单元格值
Data Operations: Filtering, Sorting, and Grouping
数据操作:筛选、排序和分组
📄 Read: references/filtering-sorting-grouping.md
When you need to:
- Implement programmatic filtering (View filtering, Column filtering)
- Enable Excel-like filter UI for users
- Apply sorting (single or multi-column)
- Group data with expand/collapse functionality
- Customize sort and group behavior
- Combine multiple data operations
- Clear or modify existing filters, sorts, or groups
📄 阅读: references/filtering-sorting-grouping.md
当你需要以下功能时:
- 实现编程式筛选(视图筛选、列筛选)
- 为用户启用类Excel的筛选UI
- 应用排序(单列或多列)
- 对数据进行分组并支持展开/折叠
- 自定义排序和分组行为
- 组合多种数据操作
- 清除或修改现有的筛选、排序或分组
Selection
选择功能
📄 Read: references/selection.md
When you need to:
- Configure selection modes (single, multiple, extended)
- Set selection units (row, cell, any)
- Select rows, columns, or cells programmatically
- Handle selection change events
- Implement CheckBox-based selection
- Disable selection for specific rows or columns
- Work with current cell and selected items
📄 阅读: references/selection.md
当你需要以下功能时:
- 配置选择模式(单选、多选、扩展选择)
- 设置选择单位(行、单元格、任意)
- 以编程方式选择行、列或单元格
- 处理选择更改事件
- 实现基于复选框的选择
- 禁用特定行或列的选择
- 处理当前单元格和选定项
Data Summaries
数据汇总
📄 Read: references/summaries.md
When you need to:
- Display group summaries (sum, average, count, min, max)
- Add table summaries at top or bottom
- Customize summary rows and formats
- Create caption summaries for groups
- Implement custom aggregate functions
- Position and style summary rows
📄 阅读: references/summaries.md
当你需要以下功能时:
- 显示组汇总(求和、平均值、计数、最小值、最大值)
- 在顶部或底部添加表格汇总
- 自定义汇总行和格式
- 为组创建标题汇总
- 实现自定义聚合函数
- 定位和设置汇总行的样式
Export to Excel and PDF
导出到Excel和PDF
📄 Read: references/export.md
When you need to:
- Export grid data to Excel or PDF
- Customize export appearance and formatting
- Export selected rows or filtered data
- Include or exclude specific columns in export
- Handle export events for customization
- Export with styles and themes
- Configure page settings for PDF export
📄 阅读: references/export.md
当你需要以下功能时:
- 将网格数据导出到Excel或PDF
- 自定义导出外观和格式
- 导出选定行或筛选后的数据
- 在导出中包含或排除特定列
- 处理导出事件以进行自定义
- 带样式和主题的导出
- 配置PDF导出的页面设置
Conditional Styling and Custom Rendering
条件样式和自定义渲染
📄 Read: references/styling.md
When you need to:
- Apply conditional styling based on cell values or row data
- Customize cell, row, and column appearance
- Handle DrawCell event for custom rendering
- Apply themes and visual styles
- Style specific cell types differently
- Implement alternating row colors
- Create custom cell renderers
📄 阅读: references/styling.md
当你需要以下功能时:
- 根据单元格值或行数据应用条件样式
- 自定义单元格、行和列的外观
- 处理DrawCell事件以进行自定义渲染
- 应用主题和视觉样式
- 为特定单元格类型设置不同的样式
- 实现交替行颜色
- 创建自定义单元格渲染器
Advanced Features
高级功能
📄 Read: references/advanced-features.md
When you need to:
- Implement master-detail views with hierarchical data
- Enable drag-and-drop operations (rows, columns)
- Localize grid text and messages for different cultures
- Serialize and deserialize grid state (columns, sorting, grouping, filtering)
- Configure grid settings and preferences
- Handle complex hierarchical data structures
📄 阅读: references/advanced-features.md
当你需要以下功能时:
- 使用分层数据实现主从视图
- 启用拖放操作(行、列)
- 为不同文化本地化网格文本和消息
- 序列化和反序列化网格状态(列、排序、分组、筛选)
- 配置网格设置和首选项
- 处理复杂的分层数据结构
Quick Start Example
快速入门示例
Here's a complete step-by-step example to create a working WinForms DataGrid application from scratch:
以下是一个完整的分步示例,用于从头开始创建一个可运行的WinForms DataGrid应用程序:
Step 1: Create Data Model Classes
步骤1:创建数据模型类
First, create classes to represent your data:
csharp
using System;
using System.Collections.ObjectModel;
public class OrderInfo
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string Country { get; set; }
public string ShipCity { get; set; }
public OrderInfo(int orderId, string customerName, string country, string customerId, string shipCity)
{
this.OrderID = orderId;
this.CustomerName = customerName;
this.Country = country;
this.CustomerID = customerId;
this.ShipCity = shipCity;
}
}
public class OrderInfoCollection
{
private ObservableCollection<OrderInfo> _orders;
public ObservableCollection<OrderInfo> Orders
{
get { return _orders; }
set { _orders = value; }
}
public OrderInfoCollection()
{
_orders = new ObservableCollection<OrderInfo>();
GenerateOrders();
}
private void GenerateOrders()
{
_orders.Add(new OrderInfo(1001, "Maria Anders", "Germany", "ALFKI", "Berlin"));
_orders.Add(new OrderInfo(1002, "Ana Trujilo", "Mexico", "ANATR", "Mexico D.F."));
_orders.Add(new OrderInfo(1003, "Antonio Moreno", "Mexico", "ANTON", "Mexico D.F."));
_orders.Add(new OrderInfo(1004, "Thomas Hardy", "UK", "AROUT", "London"));
_orders.Add(new OrderInfo(1005, "Christina Berglund", "Sweden", "BERGS", "Lula"));
_orders.Add(new OrderInfo(1006, "Hanna Moos", "Germany", "BLAUS", "Mannheim"));
_orders.Add(new OrderInfo(1007, "Frederique Citeaux", "France", "BLONP", "Strasbourg"));
_orders.Add(new OrderInfo(1008, "Martin Sommer", "Spain", "BOLID", "Madrid"));
_orders.Add(new OrderInfo(1009, "Laurence Lebihan", "France", "BONAP", "Marseille"));
_orders.Add(new OrderInfo(1010, "Elizabeth Lincoln", "Canada", "BOTTM", "Tsawassen"));
}
}首先,创建表示数据的类:
csharp
using System;
using System.Collections.ObjectModel;
public class OrderInfo
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string Country { get; set; }
public string ShipCity { get; set; }
public OrderInfo(int orderId, string customerName, string country, string customerId, string shipCity)
{
this.OrderID = orderId;
this.CustomerName = customerName;
this.Country = country;
this.CustomerID = customerId;
this.ShipCity = shipCity;
}
}
public class OrderInfoCollection
{
private ObservableCollection<OrderInfo> _orders;
public ObservableCollection<OrderInfo> Orders
{
get { return _orders; }
set { _orders = value; }
}
public OrderInfoCollection()
{
_orders = new ObservableCollection<OrderInfo>();
GenerateOrders();
}
private void GenerateOrders()
{
_orders.Add(new OrderInfo(1001, "Maria Anders", "Germany", "ALFKI", "Berlin"));
_orders.Add(new OrderInfo(1002, "Ana Trujilo", "Mexico", "ANATR", "Mexico D.F."));
_orders.Add(new OrderInfo(1003, "Antonio Moreno", "Mexico", "ANTON", "Mexico D.F."));
_orders.Add(new OrderInfo(1004, "Thomas Hardy", "UK", "AROUT", "London"));
_orders.Add(new OrderInfo(1005, "Christina Berglund", "Sweden", "BERGS", "Lula"));
_orders.Add(new OrderInfo(1006, "Hanna Moos", "Germany", "BLAUS", "Mannheim"));
_orders.Add(new OrderInfo(1007, "Frederique Citeaux", "France", "BLONP", "Strasbourg"));
_orders.Add(new OrderInfo(1008, "Martin Sommer", "Spain", "BOLID", "Madrid"));
_orders.Add(new OrderInfo(1009, "Laurence Lebihan", "France", "BONAP", "Marseille"));
_orders.Add(new OrderInfo(1010, "Elizabeth Lincoln", "Canada", "BOTTM", "Tsawassen"));
}
}Step 2: Create and Configure the DataGrid in Your Form
步骤2:在窗体中创建和配置DataGrid
csharp
using System;
using System.Windows.Forms;
using Syncfusion.WinForms.DataGrid;
using Syncfusion.WinForms.DataGrid.Enums;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private SfDataGrid sfDataGrid1;
public Form1()
{
InitializeComponent();
InitializeDataGrid();
}
private void InitializeDataGrid()
{
// Create DataGrid instance
sfDataGrid1 = new SfDataGrid();
sfDataGrid1.Dock = DockStyle.Fill;
// Create and bind data source
OrderInfoCollection collection = new OrderInfoCollection();
sfDataGrid1.DataSource = collection.Orders;
// Enable features
sfDataGrid1.AllowEditing = true;
sfDataGrid1.AllowFiltering = true;
sfDataGrid1.AllowSorting = true;
sfDataGrid1.AllowGrouping = true;
sfDataGrid1.ShowGroupDropArea = true;
// Configure selection
sfDataGrid1.SelectionMode = GridSelectionMode.Extended;
// Auto-generate columns from data model
sfDataGrid1.AutoGenerateColumns = true;
// Add to form
this.Controls.Add(sfDataGrid1);
}
}
}csharp
using System;
using System.Windows.Forms;
using Syncfusion.WinForms.DataGrid;
using Syncfusion.WinForms.DataGrid.Enums;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private SfDataGrid sfDataGrid1;
public Form1()
{
InitializeComponent();
InitializeDataGrid();
}
private void InitializeDataGrid()
{
// 创建DataGrid实例
sfDataGrid1 = new SfDataGrid();
sfDataGrid1.Dock = DockStyle.Fill;
// 创建并绑定数据源
OrderInfoCollection collection = new OrderInfoCollection();
sfDataGrid1.DataSource = collection.Orders;
// 启用功能
sfDataGrid1.AllowEditing = true;
sfDataGrid1.AllowFiltering = true;
sfDataGrid1.AllowSorting = true;
sfDataGrid1.AllowGrouping = true;
sfDataGrid1.ShowGroupDropArea = true;
// 配置选择
sfDataGrid1.SelectionMode = GridSelectionMode.Extended;
// 从数据模型自动生成列
sfDataGrid1.AutoGenerateColumns = true;
// 添加到窗体
this.Controls.Add(sfDataGrid1);
}
}
}Step 3: Define Columns Manually (Optional)
步骤3:手动定义列(可选)
If you want full control over columns instead of auto-generation:
csharp
private void InitializeDataGrid()
{
sfDataGrid1 = new SfDataGrid();
sfDataGrid1.Dock = DockStyle.Fill;
// Disable auto-generation to define columns manually
sfDataGrid1.AutoGenerateColumns = false;
// Add columns with specific properties
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "OrderID",
HeaderText = "Order ID",
Width = 100,
AllowEditing = false // Make this column read-only
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "CustomerID",
HeaderText = "Customer ID",
Width = 120
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "CustomerName",
HeaderText = "Customer Name",
Width = 150
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "Country",
HeaderText = "Country",
Width = 120
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "ShipCity",
HeaderText = "Ship City",
Width = 120
});
// Bind data source
OrderInfoCollection collection = new OrderInfoCollection();
sfDataGrid1.DataSource = collection.Orders;
// Enable features
sfDataGrid1.AllowSorting = true;
sfDataGrid1.AllowFiltering = true;
sfDataGrid1.AllowGrouping = true;
sfDataGrid1.ShowGroupDropArea = true;
// Add to form
this.Controls.Add(sfDataGrid1);
}如果你希望完全控制列,而不是自动生成:
csharp
private void InitializeDataGrid()
{
sfDataGrid1 = new SfDataGrid();
sfDataGrid1.Dock = DockStyle.Fill;
// 禁用自动生成,以便手动定义列
sfDataGrid1.AutoGenerateColumns = false;
// 添加带有特定属性的列
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "OrderID",
HeaderText = "订单ID",
Width = 100,
AllowEditing = false // 设为只读
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "CustomerID",
HeaderText = "客户ID",
Width = 120
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "CustomerName",
HeaderText = "客户名称",
Width = 150
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "Country",
HeaderText = "国家",
Width = 120
});
sfDataGrid1.Columns.Add(new GridTextColumn()
{
MappingName = "ShipCity",
HeaderText = "发货城市",
Width = 120
});
// 绑定数据源
OrderInfoCollection collection = new OrderInfoCollection();
sfDataGrid1.DataSource = collection.Orders;
// 启用功能
sfDataGrid1.AllowSorting = true;
sfDataGrid1.AllowFiltering = true;
sfDataGrid1.AllowGrouping = true;
sfDataGrid1.ShowGroupDropArea = true;
// 添加到窗体
this.Controls.Add(sfDataGrid1);
}What You'll See
运行效果
When you run the application:
- A data grid displaying 10 orders with customer information
- Click column headers to sort
- Click filter icons to filter data
- Drag column headers to the drop area to group by that column
- Double-click cells to edit (if AllowEditing is true)
- Multiple selection support with Ctrl/Shift keys
运行应用程序后,你将看到:
- 显示10条订单及客户信息的数据网格
- 点击列表头进行排序
- 点击筛选图标进行数据筛选
- 将列表头拖放到拖放区进行分组
- 双击单元格进行编辑(如果AllowEditing设为true)
- 支持使用Ctrl/Shift键进行多选
Basic Data Operations
基础数据操作
Binding Different Data Sources
绑定不同的数据源
The DataGrid supports various data source types:
csharp
// Bind to ObservableCollection (recommended for automatic UI updates)
ObservableCollection<OrderInfo> orders = new ObservableCollection<OrderInfo>();
sfDataGrid1.DataSource = orders;
// Bind to List
List<OrderInfo> orderList = new List<OrderInfo>();
sfDataGrid1.DataSource = orderList;
// Bind to DataTable
DataTable dataTable = new DataTable();
sfDataGrid1.DataSource = dataTable;
// Bind to BindingList
BindingList<OrderInfo> bindingList = new BindingList<OrderInfo>();
sfDataGrid1.DataSource = bindingList;DataGrid支持多种数据源类型:
csharp
// 绑定到ObservableCollection(推荐,支持自动UI更新)
ObservableCollection<OrderInfo> orders = new ObservableCollection<OrderInfo>();
sfDataGrid1.DataSource = orders;
// 绑定到List
List<OrderInfo> orderList = new List<OrderInfo>();
sfDataGrid1.DataSource = orderList;
// 绑定到DataTable
DataTable dataTable = new DataTable();
sfDataGrid1.DataSource = dataTable;
// 绑定到BindingList
BindingList<OrderInfo> bindingList = new BindingList<OrderInfo>();
sfDataGrid1.DataSource = bindingList;Programmatic Sorting
编程式排序
csharp
// Sort by single column ascending
sfDataGrid1.SortColumnDescriptions.Add(new SortColumnDescription()
{
ColumnName = "Country",
SortDirection = ListSortDirection.Ascending
});
// Sort by multiple columns
sfDataGrid1.SortColumnDescriptions.Add(new SortColumnDescription()
{
ColumnName = "Country",
SortDirection = ListSortDirection.Ascending
});
sfDataGrid1.SortColumnDescriptions.Add(new SortColumnDescription()
{
ColumnName = "CustomerName",
SortDirection = ListSortDirection.Descending
});
// Clear all sorting
sfDataGrid1.SortColumnDescriptions.Clear();csharp
// 按单列升序排序
sfDataGrid1.SortColumnDescriptions.Add(new SortColumnDescription()
{
ColumnName = "Country",
SortDirection = ListSortDirection.Ascending
});
// 按多列排序
sfDataGrid1.SortColumnDescriptions.Add(new SortColumnDescription()
{
ColumnName = "Country",
SortDirection = ListSortDirection.Ascending
});
sfDataGrid1.SortColumnDescriptions.Add(new SortColumnDescription()
{
ColumnName = "CustomerName",
SortDirection = ListSortDirection.Descending
});
// 清除所有排序
sfDataGrid1.SortColumnDescriptions.Clear();Programmatic Grouping
编程式分组
csharp
// Group by single column
sfDataGrid1.GroupColumnDescriptions.Add(new GroupColumnDescription()
{
ColumnName = "Country"
});
// Group by multiple levels
sfDataGrid1.GroupColumnDescriptions.Add(new GroupColumnDescription()
{
ColumnName = "Country"
});
sfDataGrid1.GroupColumnDescriptions.Add(new GroupColumnDescription()
{
ColumnName = "ShipCity"
});
// Expand/collapse all groups
sfDataGrid1.ExpandAllGroup();
sfDataGrid1.CollapseAllGroup();
// Clear all grouping
sfDataGrid1.GroupColumnDescriptions.Clear();csharp
// 按单列分组
sfDataGrid1.GroupColumnDescriptions.Add(new GroupColumnDescription()
{
ColumnName = "Country"
});
// 按多层分组
sfDataGrid1.GroupColumnDescriptions.Add(new GroupColumnDescription()
{
ColumnName = "Country"
});
sfDataGrid1.GroupColumnDescriptions.Add(new GroupColumnDescription()
{
ColumnName = "ShipCity"
});
// 展开/折叠所有组
sfDataGrid1.ExpandAllGroup();
sfDataGrid1.CollapseAllGroup();
// 清除所有分组
sfDataGrid1.GroupColumnDescriptions.Clear();Programmatic Filtering
编程式筛选
csharp
// Filter with single condition
sfDataGrid1.Columns["CustomerID"].FilterPredicates.Add(new FilterPredicate()
{
FilterType = FilterType.Equals,
FilterValue = "ALFKI"
});
// Filter with multiple OR conditions
sfDataGrid1.Columns["Country"].FilterPredicates.Add(new FilterPredicate()
{
FilterType = FilterType.Equals,
FilterValue = "Mexico",
PredicateType = PredicateType.Or
});
sfDataGrid1.Columns["Country"].FilterPredicates.Add(new FilterPredicate()
{
FilterType = FilterType.Equals,
FilterValue = "Germany",
PredicateType = PredicateType.Or
});
// Clear filter for specific column
sfDataGrid1.Columns["Country"].FilterPredicates.Clear();
// Clear all filters
foreach (var column in sfDataGrid1.Columns)
{
column.FilterPredicates.Clear();
}csharp
// 单条件筛选
sfDataGrid1.Columns["CustomerID"].FilterPredicates.Add(new FilterPredicate()
{
FilterType = FilterType.Equals,
FilterValue = "ALFKI"
});
// 多条件或筛选
sfDataGrid1.Columns["Country"].FilterPredicates.Add(new FilterPredicate()
{
FilterType = FilterType.Equals,
FilterValue = "Mexico",
PredicateType = PredicateType.Or
});
sfDataGrid1.Columns["Country"].FilterPredicates.Add(new FilterPredicate()
{
FilterType = FilterType.Equals,
FilterValue = "Germany",
PredicateType = PredicateType.Or
});
// 清除特定列的筛选
sfDataGrid1.Columns["Country"].FilterPredicates.Clear();
// 清除所有筛选
foreach (var column in sfDataGrid1.Columns)
{
column.FilterPredicates.Clear();
}Handling Selection Events
处理选择事件
csharp
// Handle selection changed
sfDataGrid1.SelectionChanged += (sender, e) =>
{
if (sfDataGrid1.SelectedItem != null)
{
var selectedOrder = sfDataGrid1.SelectedItem as OrderInfo;
Console.WriteLine($"Selected: {selectedOrder.CustomerName}");
}
};
// Handle cell value changed
sfDataGrid1.CurrentCellValueChanged += (sender, e) =>
{
var rowData = sfDataGrid1.GetRecordAtRowIndex(e.RowColumnIndex.RowIndex);
Console.WriteLine($"Cell value changed in row: {e.RowColumnIndex.RowIndex}");
};csharp
// 处理选择更改事件
sfDataGrid1.SelectionChanged += (sender, e) =>
{
if (sfDataGrid1.SelectedItem != null)
{
var selectedOrder = sfDataGrid1.SelectedItem as OrderInfo;
Console.WriteLine($"已选择: {selectedOrder.CustomerName}");
}
};
// 处理单元格值更改事件
sfDataGrid1.CurrentCellValueChanged += (sender, e) =>
{
var rowData = sfDataGrid1.GetRecordAtRowIndex(e.RowColumnIndex.RowIndex);
Console.WriteLine($"行 {e.RowColumnIndex.RowIndex} 中的单元格值已更改");
};Common Patterns
常见模式
Pattern 1: Manual Column Definition with Selection
模式1:手动定义列并配置选择
csharp
sfDataGrid.AutoGenerateColumns = false;
// Add columns
sfDataGrid.Columns.Add(new GridTextColumn()
{
MappingName = "OrderID",
HeaderText = "Order ID",
AllowEditing = false
});
sfDataGrid.Columns.Add(new GridNumericColumn()
{
MappingName = "Quantity",
HeaderText = "Qty"
});
// Configure selection
sfDataGrid.SelectionMode = GridSelectionMode.Multiple;
sfDataGrid.SelectionUnit = GridSelectionUnit.Row;csharp
sfDataGrid.AutoGenerateColumns = false;
// 添加列
sfDataGrid.Columns.Add(new GridTextColumn()
{
MappingName = "OrderID",
HeaderText = "订单ID",
AllowEditing = false
});
sfDataGrid.Columns.Add(new GridNumericColumn()
{
MappingName = "Quantity",
HeaderText = "数量"
});
// 配置选择
sfDataGrid.SelectionMode = GridSelectionMode.Multiple;
sfDataGrid.SelectionUnit = GridSelectionUnit.Row;Pattern 2: Filtering, Sorting, and Grouping
模式2:筛选、排序和分组
csharp
// Enable UI features
sfDataGrid.AllowFiltering = true;
sfDataGrid.AllowSorting = true;
sfDataGrid.AllowGrouping = true;
sfDataGrid.ShowGroupDropArea = true;
// Programmatic operations
sfDataGrid.Columns["CustomerID"].FilterPredicates.Add(
new FilterPredicate() { FilterType = FilterType.Equals, FilterValue = "FRANS" });
sfDataGrid.SortColumnDescriptions.Add(
new SortColumnDescription() { ColumnName = "OrderDate", SortDirection = ListSortDirection.Descending });
sfDataGrid.GroupColumnDescriptions.Add(
new GroupColumnDescription() { ColumnName = "Country" });csharp
// 启用UI功能
sfDataGrid.AllowFiltering = true;
sfDataGrid.AllowSorting = true;
sfDataGrid.AllowGrouping = true;
sfDataGrid.ShowGroupDropArea = true;
// 编程式操作
sfDataGrid.Columns["CustomerID"].FilterPredicates.Add(
new FilterPredicate() { FilterType = FilterType.Equals, FilterValue = "FRANS" });
sfDataGrid.SortColumnDescriptions.Add(
new SortColumnDescription() { ColumnName = "OrderDate", SortDirection = ListSortDirection.Descending });
sfDataGrid.GroupColumnDescriptions.Add(
new GroupColumnDescription() { ColumnName = "Country" });Pattern 3: Conditional Styling
模式3:条件样式
csharp
sfDataGrid.DrawCell += (sender, e) =>
{
if (e.DataRow.RowType == RowType.DefaultRow && e.Column.MappingName == "Quantity")
{
var quantity = Convert.ToInt32(e.DisplayText);
if (quantity < 10)
{
e.Style.BackColor = Color.LightCoral;
e.Style.TextColor = Color.White;
}
else if (quantity > 50)
{
e.Style.BackColor = Color.LightGreen;
}
}
};csharp
sfDataGrid.DrawCell += (sender, e) =>
{
if (e.DataRow.RowType == RowType.DefaultRow && e.Column.MappingName == "Quantity")
{
var quantity = Convert.ToInt32(e.DisplayText);
if (quantity < 10)
{
e.Style.BackColor = Color.LightCoral;
e.Style.TextColor = Color.White;
}
else if (quantity > 50)
{
e.Style.BackColor = Color.LightGreen;
}
}
};Pattern 4: Export to Excel
模式4:导出到Excel
csharp
using Syncfusion.WinForms.DataGridConverter;
var options = new DataGridExcelExportOptions();
options.ExportMode = ExportMode.Value;
options.ExcludeColumns = new List<string> { "InternalID" };
var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
var workbook = excelEngine.Excel.Workbooks[0];
workbook.SaveAs("GridData.xlsx");csharp
using Syncfusion.WinForms.DataGridConverter;
var options = new DataGridExcelExportOptions();
options.ExportMode = ExportMode.Value;
options.ExcludeColumns = new List<string> { "InternalID" };
var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
var workbook = excelEngine.Excel.Workbooks[0];
workbook.SaveAs("GridData.xlsx");Pattern 5: Summaries
模式5:汇总功能
csharp
// Add group summary
var groupSummary = new GridSummaryRow();
groupSummary.ShowSummaryInRow = false;
groupSummary.SummaryColumns.Add(new GridSummaryColumn()
{
Name = "TotalQuantity",
MappingName = "Quantity",
SummaryType = SummaryType.Int32Aggregate,
Format = "Total: {Sum}",
});
sfDataGrid.GroupSummaryRows.Add(groupSummary);
// Add table summary
var tableSummary = new GridTableSummaryRow();
tableSummary.ShowSummaryInRow = false;
tableSummary.Position = TableSummaryRowPosition.Bottom;
tableSummary.SummaryColumns.Add(new GridSummaryColumn()
{
Name = "GrandTotal",
MappingName = "UnitPrice",
SummaryType = SummaryType.DoubleAggregate,
Format = "Grand Total: ${Sum:C}",
});
sfDataGrid.TableSummaryRows.Add(tableSummary);csharp
// 添加组汇总
var groupSummary = new GridSummaryRow();
groupSummary.ShowSummaryInRow = false;
groupSummary.SummaryColumns.Add(new GridSummaryColumn()
{
Name = "TotalQuantity",
MappingName = "Quantity",
SummaryType = SummaryType.Int32Aggregate,
Format = "总计: {Sum}",
});
sfDataGrid.GroupSummaryRows.Add(groupSummary);
// 添加表格汇总
var tableSummary = new GridTableSummaryRow();
tableSummary.ShowSummaryInRow = false;
tableSummary.Position = TableSummaryRowPosition.Bottom;
tableSummary.SummaryColumns.Add(new GridSummaryColumn()
{
Name = "GrandTotal",
MappingName = "UnitPrice",
SummaryType = SummaryType.DoubleAggregate,
Format = "总计: ${Sum:C}",
});
sfDataGrid.TableSummaryRows.Add(tableSummary);Key Properties
关键属性
Core Grid Properties
核心网格属性
- - The data source to bind
DataSource - - Enable/disable automatic column generation
AutoGenerateColumns - - Enable/disable editing
AllowEditing - - Enable/disable filtering
AllowFiltering - - Enable/disable sorting
AllowSorting - - Enable/disable grouping
AllowGrouping - - Enable/disable column reordering
AllowDraggingColumns - - Enable/disable row reordering
AllowDraggingRows
- - 要绑定的数据源
DataSource - - 启用/禁用自动列生成
AutoGenerateColumns - - 启用/禁用编辑
AllowEditing - - 启用/禁用筛选
AllowFiltering - - 启用/禁用排序
AllowSorting - - 启用/禁用分组
AllowGrouping - - 启用/禁用列重排序
AllowDraggingColumns - - 启用/禁用行重排序
AllowDraggingRows
Selection Properties
选择属性
- - Single, Multiple, Extended, None
SelectionMode - - Row, Cell, Any
SelectionUnit - - Get/set selected item
SelectedItem - - Get/set multiple selected items
SelectedItems
- - 单选、多选、扩展选择、无
SelectionMode - - 行、单元格、任意
SelectionUnit - - 获取/设置选定项
SelectedItem - - 获取/设置多个选定项
SelectedItems
Visual Properties
视觉属性
- - Height of header row
HeaderRowHeight - - Default row height
RowHeight - - Grid styling options
Style - - Show/hide group drop area
ShowGroupDropArea - - Show/hide row headers
ShowRowHeader
- - 表头行高度
HeaderRowHeight - - 默认行高度
RowHeight - - 网格样式选项
Style - - 显示/隐藏分组拖放区
ShowGroupDropArea - - 显示/隐藏行表头
ShowRowHeader
Common Use Cases
常见用例
Use Case 1: E-commerce Order Management
用例1:电商订单管理
Display orders with filtering by status, sorting by date, grouping by customer, editing for updates, and conditional styling for priority orders.
显示订单,支持按状态筛选、按日期排序、按客户分组、编辑更新,以及为优先级订单应用条件样式。
Use Case 2: Financial Reporting
用例2:财务报表
Show transaction data with summaries (totals, averages), export to Excel/PDF, conditional styling for negative values, and master-detail for transaction details.
显示交易数据,包含汇总(总计、平均值)、导出到Excel/PDF、为负值应用条件样式,以及交易详情的主从视图。
Use Case 3: Inventory Management
用例3:库存管理
Track products with filtering by category, low-stock conditional styling, editing for quantity updates, and selection for bulk operations.
跟踪产品,支持按类别筛选、为低库存应用条件样式、编辑数量更新,以及选择进行批量操作。
Use Case 4: Customer Relationship Management
用例4:客户关系管理
Manage contacts with multi-column sorting, grouping by region, export capabilities, and custom rendering for status indicators.
管理联系人,支持多列排序、按地区分组、导出功能,以及为状态指示器进行自定义渲染。
Use Case 5: Project Management
用例5:项目管理
Display tasks with master-detail for subtasks, drag-drop for reordering, conditional styling by status, and summaries for progress tracking.
显示任务,支持子任务的主从视图、拖放重排序、按状态应用条件样式,以及进度跟踪的汇总。
Troubleshooting
故障排除
For common issues and solutions:
- Column not displaying: Check MappingName matches property name exactly (case-sensitive)
- Editing not working: Verify both grid-level and column-level AllowEditing properties
- Filter not applying: Ensure AllowFiltering is enabled and call RefreshFilter() after programmatic changes
- Export formatting issues: Customize export options and handle export events
- Styling not visible: Ensure DrawCell event is wired and Style properties are set correctly
- Selection not working: Check SelectionMode and SelectionUnit are properly configured
Refer to the specific reference files above for detailed troubleshooting guidance in each feature area.
常见问题及解决方案:
- 列未显示:检查MappingName与属性名称完全匹配(区分大小写)
- 编辑无法工作:验证网格级别和列级别的AllowEditing属性
- 筛选未应用:确保AllowFiltering已启用,并在编程式更改后调用RefreshFilter()
- 导出格式问题:自定义导出选项并处理导出事件
- 样式未显示:确保已绑定DrawCell事件并正确设置Style属性
- 选择无法工作:检查SelectionMode和SelectionUnit是否正确配置
有关各功能区域的详细故障排除指南,请参阅上述特定的参考文件。