作者:海雅
一、取得數據表 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();
&n
bsp; 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
}