C# DataGridView 创建行并赋值的详细指南
C# DataGridView 创建行并赋值
在使用 C# Windows Forms 应用程序时,DataGridView 控件提供了一种强大且灵活的方式来显示和编辑表格数据。本文将指导您完成在 DataGridView 中创建行并为其赋值的步骤。
以下是使用 C# 为 DataGridView 创建行并赋值的示例代码:
using System;
using System.Data;
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');
// 创建并添加新行
int newRow = dataGridView.Rows.Add();
// 为新行中的单元格赋值
dataGridView.Rows[newRow].Cells['Name'].Value = 'John';
dataGridView.Rows[newRow].Cells['Age'].Value = 25;
dataGridView.Rows[newRow].Cells['City'].Value = 'New York';
// 将 DataGridView 添加到窗口中
form.Controls.Add(dataGridView);
// 显示窗口
Application.Run(form);
}
}
代码解释:
-
创建 DataGridView 控件和列: 首先,我们创建一个
DataGridView对象并使用Dock属性将其设置为填充整个窗体。然后,我们使用Columns.Add()方法添加三列:'Name'、'Age' 和 'City'。 -
添加新行: 使用
dataGridView.Rows.Add()方法添加一个新行到 DataGridView。此方法返回新行的索引。 -
为单元格赋值: 通过使用新行的索引和列名,我们可以访问每个单元格并使用
Value属性为其分配值。 -
显示 DataGridView: 最后,将 DataGridView 控件添加到窗体中,并运行应用程序以显示结果。
总结:
通过使用 Rows 属性、Add 方法以及索引或列名,您可以轻松地在 C# DataGridView 控件中创建行并为其赋值。此方法提供了添加和管理数据的强大功能,使 DataGridView 成为构建 Windows Forms 应用程序的宝贵工具。
原文地址: https://www.cveoy.top/t/topic/SMU 著作权归作者所有。请勿转载和采集!