c# dataGridView控件如何生成三行三列的表格
时间: 2024-09-18 21:07:08 浏览: 36
在C#中,DataGridView控件用于显示和编辑数据,通常通过数据源(如DataTable、BindingSource等)来填充它。为了生成一个三行三列的基本表格,你可以创建一个新的DataTable,然后绑定到DataGridView。以下是步骤:
1. 创建一个新的DataTable:
```csharp
DataTable dataTable = new DataTable();
```
2. 添加列(假设列名为"Column1", "Column2", 和 "Column3"):
```csharp
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
dataTable.Columns.Add("Column3");
```
3. 生成并添加三行数据:
```csharp
for (int i = 1; i <= 3; i++)
{
DataRow newRow = dataTable.NewRow();
newRow["Column1"] = "Row " + i + ", Column 1";
newRow["Column2"] = "Row " + i + ", Column 2";
newRow["Column3"] = "Row " + i + ", Column 3";
dataTable.Rows.Add(newRow);
}
```
4. 将DataTable绑定到DataGridView:
```csharp
dataGridView.DataSource = dataTable;
```
5. 最后,显示数据网格控件:
```csharp
this.dataGridView.Visible = true;
```
完整的例子可能会放在Form_Load事件或某个按钮的Click事件处理中。
```csharp
private void Form1_Load(object sender, EventArgs e)
{
//...
CreateTable();
}
private void CreateTable()
{
// 创建表格
DataTable dataTable = new DataTable();
// 添加列
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
dataTable.Columns.Add("Column3");
// 添加行
for (int i = 1; i <= 3; i++)
{
DataRow newRow = dataTable.NewRow();
newRow["Column1"] = "Row " + i + ", Column 1";
newRow["Column2"] = "Row " + i + ", Column 2";
newRow["Column3"] = "Row " + i + ", Column 3";
dataTable.Rows.Add(newRow);
}
// 绑定到 DataGridView
dataGridView.DataSource = dataTable;
}
```
阅读全文