Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# datagrid

作者:顺我者未必能活   发布日期:2025-02-27   浏览:105

using System;
using System.Windows.Forms;
using System.Data;

namespace DataGridExample
{
    public class Form1 : Form
    {
        private DataGridView dataGridView1;

        public Form1()
        {
            // 创建DataGridView控件
            dataGridView1 = new DataGridView();
            dataGridView1.Dock = DockStyle.Fill;

            // 添加DataGridView到窗体
            this.Controls.Add(dataGridView1);

            // 设置DataGridView的数据源
            BindData();
        }

        private void BindData()
        {
            // 创建一个DataTable来存储数据
            DataTable dt = new DataTable();

            // 添加列
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Age", typeof(int));

            // 添加行
            dt.Rows.Add(1, "Alice", 25);
            dt.Rows.Add(2, "Bob", 30);
            dt.Rows.Add(3, "Charlie", 35);

            // 将DataTable绑定到DataGridView
            dataGridView1.DataSource = dt;
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

解释说明

  1. 创建DataGridView控件:在构造函数中,我们创建了一个 DataGridView 控件,并将其 Dock 属性设置为 Fill,以便它填充整个窗体。

  2. 添加DataGridView到窗体:使用 this.Controls.Add(dataGridView1)DataGridView 添加到窗体中。

  3. 设置DataGridView的数据源:通过调用 BindData() 方法,我们将一个 DataTable 绑定到 DataGridViewDataSource 属性。这样,DataGridView 就会显示 DataTable 中的数据。

  4. 创建和填充DataTable:在 BindData() 方法中,我们创建了一个 DataTable,并向其中添加了三列(ID、Name 和 Age),然后添加了几行数据。

  5. 运行应用程序:在 Main 方法中,我们启动了应用程序并显示窗体。

这个示例展示了如何在 C# WinForms 应用程序中使用 DataGridView 控件来显示表格数据。

上一篇:c#递归

下一篇:c#try

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站