作者:海雅
一、取得資料表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;//drdr["ClassID"].ToString().Trim()).Selected=true;//drn.DataRow三、分類為DataRow三、分類為DataRow三、分類為DataRow
三、分類為DataRow三、分類為DataRow三、分類為DataRow三、分類為DataRow三、分類為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
}