C#中使用DataGridView控件显示DataTable中的数据

DataGridView中显示DataTable数据有以下两种方式:
1.独立的DataTable:
  直接将DataGridView的DataSource属性设置为DataTable对象;
2.DataSet中的DataTable:
  将DataGridView的DataSource属性设置为包含DataTable的DataSet对象,
  再将DataMember属性设置为DataTable名。

实例:
TestDataGridViewDataTable:

Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace TestDataGridViewDataTable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //单独的DataTable
        private void button1_Click(object sender, EventArgs e)
        {
            string select = "Select id, username, password, email FROM TestUser";
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MGC"].ConnectionString))
            {
                conn.Open();
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(select, conn);
                da.Fill(ds, "TestUser");
                dataGridView1.AutoGenerateColumns = true;
                dataGridView1.DataSource = ds.Tables["TestUser"];

                conn.Close();
            }
        }

        //DataSet中的DataTable
        private void button2_Click(object sender, EventArgs e)
        {
            string select = "Select id, username, password, email FROM TestUser";
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MGC"].ConnectionString))
            {
                conn.Open();
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(select, conn);
                da.Fill(ds, "TestUser");
                dataGridView1.AutoGenerateColumns = true;
                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = "TestUser";

                conn.Close();
            }
        }
    }
}


App.config:


  
    
  


转自:http://mgc.name/article.asp?id=690

你可能感兴趣的:(C#)