如何在C#windows窗体中显示数据库

我做了一个C#DataSet连接access数据库,但是不知道怎样让它显示在窗体中,这是我的代码:

namespace DataSet
{
class Program
{
static void Fun(string[] args)
{ // Creat conection object for Microsoft Access OLE DB Provider;
//note @ sign prefacing string literal so backslashes in path name;
//work
OleDbConnection thisConnection = new OleDbConnection(
@"provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\c#教程\协和医院.mdb");
// Creat DataAdapter object
OleDbDataAdapter thisAdapter = new OleDbDataAdapter(
"SELECT ID, 字段1,字段2,字段3,字段4,字段5,字段6,字段7,字段8 FROM Sheet1", thisConnection);
// Create DataSet to contain related data tables,rows and columns
System.Data.DataSet thisDataSet = new System.Data.DataSet();
//Fill DataSet using query defined previously for DataAdapter
thisAdapter.Fill(thisDataSet, "Sheet1");
foreach (DataRow theRow in thisDataSet.Tables["Sheet1"].Rows)
dataGridView1.DataSource = dataset.Tables
{
Console.WriteLine(theRow["ID"] + "\t" + theRow["字段1"] + "\t" +
theRow["字段2"] + "\t" + theRow["字段3"] + "\t" +
theRow["字段4"] + "\t" +
theRow["字段5"] + "\t" +
theRow["字段6"] + "\t" +
theRow["字段7"] + "\t" +
theRow["字段8"]);
}
thisConnection.Close();
Console.Write("Program finished,press Enter /Return to continue:");
Console.ReadLine();
}

}
}

希望大家多帮忙啊,越详细越好,谢谢

在工具栏拖一个datagridview控件到form1中,下面是实现代码:

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.OleDb;

namespace text01

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            OleDbConnection thisConnection = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:\text01\text01\DB\协和医院.mdb");

            string sql = "select * from Sheet1";

            OleDbDataAdapter thisAdapter = new OleDbDataAdapter(sql, thisConnection);

            System.Data.DataSet thisDataSet = new System.Data.DataSet();

            thisAdapter.Fill(thisDataSet, "table");

            DataTable dt = thisDataSet.Tables["table"];

            this.dataGridView1.DataSource = dt;

            thisConnection.Close();

        }

    }

}

效果图:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-08-17
工具栏有数据相关的组件,DataSet,BingdingSource,DataGridView,把这三个加到窗体上。先要设置DataSet,前提你已经添加了数据源,那么弹出的对话框你直接确定就好。然后设置BingdingSource的DataSource属性,下拉选中什么什么示例下面的DataSet,当然此时它已经有了具体的名字了。然后设置DataGridView,在界面上选中它,右上角会有个下拉选项,点开它,设置数据源为BingdingSource下你要显示的表。
第2个回答  2010-08-17
拖一个dataGridView控件,将数据源赋值为dataset中的表如:
dataGridView1.DataSource = dataset.Tables[0];
前提是你要先向dataset中填充数据。
相似回答