本文給出了使用ASP.NET進行數據庫時的程序實現源代碼,比如取得數據表 i 行 j 列的值;將數據讀入DropDownList和分類編碼檢索出相應的分類名稱並在DataGrid中顯示,供大家參考!
一、取得數據表 i 行 j 列的值
//建立並打開數據庫連接
OleDbConnection conn=new OleDbConnection();
conn.ConnectionString=strConnectionString;//strConnectionString為數據庫連接字符串
conn.Open();
string sql="select * from NewsClass order by ClassId desc";
string x;
DataSet ds=new DataSet();
OleDbDataAdapter da=new OleDbDataAdapter(sql,conn);
da.Fill(ds,"NewsTable");
DataTable dt=ds.Tables["NewsTable"];
x=dt.Rows[i][1].ToString()//數據表i行j列的值
conn.close();
二、將數據讀入DropDownList
(1)DropDownList中添加數據
//建立並打開數據庫連接
OleDbConnection conn=new OleDbConnection();
conn.ConnectionString=strConnectionString;//strConnectionString為數據庫連接字符串
conn.Open();
string sql="select * from NewsClass order by ClassId desc";
//建立數據集
DataSet ds=new DataSet();
OleDbDataAdapter da=new OleDbDataAdapter(sql,conn);
da.Fill(ds,"NewsTable");
this.DropDownList1.DataSource=ds;
this.DropDownList1.DataTextField = "ClassName";//Text值
this.DropDownList1.DataValueField = "ClassID";//Value值
this.DropDownList1.DataBind();
conn.Close();
(2)選中DropDownList的某項
this.DropDownList1.Items.FindByValue(dr["ClassID"].ToString().Trim()).Selected=true;
//dr為DataRow
三、分類編碼檢索出相應的分類名稱並在DataGrid中顯示
(1).ASPX中的代碼(ClassID為分類編碼)
<asp:TemplateColumn HeaderText="類 別">
<ItemTemplate>
<asp:Label id=lblClass runat="server"
Text='<%# GetClassName(Convert.ToInt32(DataBinder.Eval(Container,
"DataItem.ClassID"))) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
(2)C#代碼
///
/// "分類"列根據數字返回文字
///
///
///
public string GetClassName(int ClassID)
{
OleDbConnection conn=new OleDbConnection();
conn.ConnectionString=strConnectionString;
conn.Open();
string sql="select * from NewsClass where ClassID="+ClassID;
DataSet ds=new DataSet();
OleDbDataAdapter da=new OleDbDataAdapter(sql,conn);
da.Fill(ds,"ClassTable");
DataTable dt=ds.Tables["ClassTable"];
string strClassName=dt.Rows[0]["ClassName"].ToString();
conn.Close();
return strClassName;//返回 ClassID對應的ClassName
}