作者:海雅
一、取得数据表i行j列的值
//建立并打开数据库连接
OleDbConnectionconn=newOleDbConnection();
conn.ConnectionString=strConnectionString;//strConnectionString为数据库连接字符串
conn.Open();
stringsql="select*fromNewsClassorderbyClassIddesc";
stringx;
DataSetds=newDataSet();
OleDbDataAdapterda=newOleDbDataAdapter(sql,conn);
da.Fill(ds,"NewsTable");
DataTabledt=ds.Tables["NewsTable"];
x=dt.Rows[i][1].ToString()//数据表i行j列的值
conn.close();
二、将数据读入DropDownList
(1)DropDownList中添加数据
//建立并打开数据库连接
OleDbConnectionconn=newOleDbConnection();
conn.ConnectionString=strConnectionString;//strConnectionString为数据库连接字符串
conn.Open();
stringsql="select*fromNewsClassorderbyClassIddesc";
//建立数据集
DataSetds=newDataSet();
OleDbDataAdapterda=newOleDbDataAdapter(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:TemplateColumnHeaderText="类别">
<ItemTemplate>
<asp:Labelid=lblClassrunat="server"Text='<%#GetClassName(Convert.ToInt32(DataBinder.Eval(Container,"DataItem.ClassID")))%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
(2)C#代码:
///<summary>
///"分类"列根据数字返回文字
///</summary>
///<paramname="IsPassed"></param>
///<returns></returns>
publicstringGetClassName(intClassID)
{
OleDbConnectionconn=newOleDbConnection();
conn.ConnectionString=strConnectionString;
conn.Open();
stringsql="select*fromNewsClasswhereClassID="+ClassID;
DataSetds=newDataSet();
OleDbDataAdapterda=newOleDbDataAdapter(sql,conn);
da.Fill(ds,"ClassTable");
DataTabledt=ds.Tables["ClassTable"];
stringstrClassName=dt.Rows[0]["ClassName"].ToString();
conn.Close();
returnstrClassName;//返回ClassID对应的ClassName
}