当前位置:首页 > ASP.NET与数据库相关技巧

ASP.NET与数据库相关技巧

点击次数:775  更新日期:2010-12-29
\n

一、取得数据表 i 行 j 列的值


\n


\n

\n


\n

//建立并打开数据库连接

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();


\n

二、将数据读入DropDownList


\n

(1)DropDownList中添加数据


\n


\n

\n


\n

//建立并打开数据库连接

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();


\n

(2)选中DropDownList的某项


\n


\n

\n


\n

this.DropDownList1.Items.FindByValue(dr["ClassID"].ToString().Trim()).Selected=true;

//dr为DataRow


\n

三、分类编码检索出相应的分类名称并在DataGrid中显示


\n

(1).ASPX中的代码(ClassID为分类编码)


\n


\n

\n


\n

<asp:TemplateColumn HeaderText=”类 别”>

<ItemTemplate>

<asp:Label id=lblClass runat=”server”

Text=’<%# GetClassName(Convert.ToInt32(DataBinder.Eval(Container,

“DataItem.ClassID”))) %>’>

</asp:Label>

</ItemTemplate>

</asp:TemplateColumn>


\n


\n

(2)C#代码


\n


\n

\n


\n

///



/// “分类”列根据数字返回文字

///

///

///

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

}

\n