使access數(shù)據(jù)庫,適合初學者,修改連接、查詢語句后可直接運行,代碼中有注明。
填充dataset的步驟
1、使用數(shù)據(jù)庫連接字符串創(chuàng)建數(shù)據(jù)庫連接對象
2、用sql查詢語句和數(shù)據(jù)庫連接對象創(chuàng)建數(shù)據(jù)庫適配器dataadapter
3、使用dataadapter的fill 方法填充dataset
using system;
using system.windows.forms;
using system.data;
using system.data.sqlclient;
using system.data.oledb;
//professional c# 2nd的datagrid實例
/**//// <summary>
/// this class provides an example of creating and using a data grid.
/// </summary>
public class displaytabulardata : system.windows.forms.form
{
private system.windows.forms.button retrievebutton;
private system.windows.forms.datagrid datagrid;
/**//// <summary>
/// construct the window.
/// </summary>
/// <remarks>
/// this method constructs the window by creating both the data grid and the button.
/// </remarks>
public displaytabulardata()
{
this.autoscalebasesize = new system.drawing.size(5, 13);
this.clientsize = new system.drawing.size(464, 253);
this.text = "01_displaytabulardata";
this.datagrid = new system.windows.forms.datagrid();
datagrid.begininit();
datagrid.location = new system.drawing.point(8, 8);
datagrid.size = new system.drawing.size(448, 208);
datagrid.tabindex = 0;
datagrid.anchor = anchorstyles.bottom | anchorstyles.top | anchorstyles.left | anchorstyles.right;
this.controls.add(this.datagrid);
datagrid.endinit();
this.retrievebutton = new system.windows.forms.button();
retrievebutton.location = new system.drawing.point(384, 224);
retrievebutton.size = new system.drawing.size(75, 23);
retrievebutton.tabindex = 1;
retrievebutton.anchor = anchorstyles.bottom | anchorstyles.right;
retrievebutton.text = "retrieve";
retrievebutton.click += new system.eventhandler(this.retrievebutton_click);
this.controls.add(this.retrievebutton);
}
/**//// <summary>
/// retrieve the data
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
protected void retrievebutton_click(object sender, system.eventargs e)
{
retrievebutton.enabled = false;
string source = @"provider=microsoft.jet.oledb.4.0;data source=c:/documents and settings/manio/my documents/printmanager/program/printmanagev1/database/printdb.mdb";
string select = "select * from maininfo";
/**/////////////////////////////////
//填充dataset的步驟
//1、使用數(shù)據(jù)庫連接字符串創(chuàng)建數(shù)據(jù)庫連接對象
// 2、用sql查詢語句和數(shù)據(jù)庫連接對象創(chuàng)建數(shù)據(jù)庫適配器dataadapter
// 3、使用dataadapter的fill 方法填充dataset
oledbconnection olecon = new oledbconnection(source);
oledbdataadapter da = new oledbdataadapter(select,olecon);
dataset ds = new dataset();
da.fill(ds, "maininfo");
datagrid.setdatabinding(ds, "maininfo"); //datagrid的數(shù)據(jù)綁定,使用dataset 和 數(shù)據(jù)庫的表名
}
/**//// <summary>
/// display the application window
/// </summary>
static void main()
{
application.run(new displaytabulardata());
}
}
新聞熱點
疑難解答
圖片精選