C# DataGridView Database Connection Guide

To connect a database with a DataGridView in C#, you can follow these steps:

  1. Add a DataGridView control to the form and name it dataGridView1.
  2. Import the System.Data.SqlClient namespace.
  3. Create a database connection object SqlConnection and set the connection string.
  4. Create a data adapter object SqlDataAdapter.
  5. Create a DataSet object.
  6. Fill the dataset using SqlDataAdapter in the form’s Load event.
  7. Bind the dataset to the DataGridView control.

Here is an example piece of code:

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

namespace DataGridViewDatabase
{
    public partial class Form1 : Form
    {
        // 创建数据库连接对象
        SqlConnection conn = new SqlConnection("Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建数据适配器对象
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM YourTable", conn);

            // 创建数据集对象
            DataSet ds = new DataSet();

            // 填充数据到数据集
            da.Fill(ds);

            // 绑定数据集到DataGridView控件
            dataGridView1.DataSource = ds.Tables[0];
        }
    }
}

In the example above, you will need to replace “YourServer”, “YourDatabase”, and “YourTable” with the actual database server, database name, and table name. This will allow you to connect to the database and display data using DataGridView in C#.

bannerAds