一、取得資料表 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#代碼:
/// <summary>
/// "分類"列根據數字返迴文字
/// </summary>
/// <param name="IsPassed"></param>
/// <returns></returns>
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
}