前台获取后台datatable

本文介绍两种在ASP.NET中加载并显示数据的方法:一是使用DataTable进行数据绑定,需确保DataTable为全局变量;二是通过拼接字符串的方式生成HTML代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:

前台代码:

 

代码
<div>
<%for (int i = 0; i < dtTitle.Rows.Count; i++)
{
%>
<div style="float:left;">
<a href="Default2.aspx?id=<%Response.Write(dtTitle.Rows[i]["ID"].ToString()); %>">
<%Response.Write(dtTitle.Rows[i]["title"].ToString()); %>
</a></div>
<%} %>
</div>

 

 

后台代码:

 

代码
public partial class _Default : System.Web.UI.Page
{
public DataTable dtTitle = null;
protected void Page_Load(object sender, EventArgs e)
{
getData();
}
protected void getData()
{
string sql = "select top 5 * from viewTitle where isview=1";
DataSet dsTitle
= DbHelperOleDb.Query(sql);
dtTitle
= dsTitle.Tables[0];
}
}

注意:public DataTable dtTitle = null;

datatable要是全局的。不然前台读不到datatable。

 

方法二(拼接字符串):

前台代码:用<%=str%>绑定后台变量;

 

<li>
<a href="#">新闻资讯</a>
<ul style="width:183px; display: inline; margin-left: 25px; font-size: 14px; font-weight: bold;">
<%=str%>
</ul>

</li>

 

后台代码:

 

 

代码
public StringBuilder str = new StringBuilder();//注意这里要public
protected void Page_Load(object sender, EventArgs e)
{
string SQLString = "select * from productclass where productid=0";
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
DataSet ds
= new DataSet();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
OleDbCommand command
= new OleDbCommand(SQLString, connection);
OleDbDataAdapter da
= new OleDbDataAdapter(command);
da.Fill(ds,
"ds");
}
catch (System.Data.OleDb.OleDbException ex)
{
throw new Exception(ex.Message);
}
}
DataTable dt
= ds.Tables[0];
int count = dt.Rows.Count;
for (int i = 0; i < count; i++)
{
str.Append(
"<li style=\"width: 113px; display: inline;margin-top: 15px;\">");
str.Append(
"<a title=" + (dt.Rows[i]["productname"]).ToString() + " href=\"NewsList.aspx?id=" + Convert.ToInt32(dt.Rows[i]["id"]) + "\"");
str.Append(
" style=\"color: #FDFC89\"");
str.Append(
">");
str.Append(
"" + dt.Rows[i]["productname"].ToString() + "");
str.Append(
"</a>");
str.Append(
"</li>");
}
//Response.Write(str);
}

 

 

 

转载于:https://www.cnblogs.com/sheseido/archive/2010/11/24/1886413.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值