如何在C#windows窗体中显示数据库
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();
}
}
}
效果图:
dataGridView1.DataSource = dataset.Tables[0];
前提是你要先向dataset中填充数据。