前台获取后台datatable

方法一:

前台代码:

代码
<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="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=\" 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/p/1886413.html