我对 ASP.NET 相当陌生,作为一项自我选择的任务,我将创建一个简单的博客。它几乎完成了,但我遇到了一个问题。从代码中可以看出,我首先使用查询从我的 SQL 服务器数据库中返回博客条目的数量。然后,for 循环从所有行中读取标题、日期和文本内容,并创建一个 html div 并将它们加载到其中。 效果很好,除了一件事:ExecuteScalar() 只读取第一行,这将为每次迭代返回相同的值,导致所有博客条目都相同。
我需要一种方法让读者在每次迭代中继续前进。我考虑过将 SQLbulkcopy 制作到另一个表中,然后我可以从 for 循环中删除第一行,但这似乎会在每个 Page_Load 上执行该操作会减慢页面相当多的速度。
string SQLreadTitle = "Select BLOG.BlogTitle from BLOG order by BlogID DESC";
string SQLreadDate = "Select BLOG.BlogDate from BLOG order by BlogID DESC";
string SQLreadText = "Select BLOG.BlogText from BLOG order by BlogID DESC";
string SQLcountIDs = "Select count(BlogID) from BLOG";
protected void Page_Load(object sender, EventArgs e)
{
int i;
SqlConnection con = new SqlConnection(cnString);
con.Open();
SqlCommand countIDs = new SqlCommand(SQLcountIDs, con);
int count = Convert.ToInt32(countIDs.ExecuteScalar());
for (i = 0; i < count; i++)
{
SqlCommand readTitle = new SqlCommand(SQLreadTitle, con);
string titleString = readTitle.ExecuteScalar().ToString();
SqlCommand readDate = new SqlCommand(SQLreadDate, con);
string dateString = readDate.ExecuteScalar().ToString();
SqlCommand readText = new SqlCommand(SQLreadText, con);
string textString = readText.ExecuteScalar().ToString();
System.Web.UI.HtmlControls.HtmlGenericControl dynDiv =
new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
dynDiv.ID = "BlogPost";
dynDiv.InnerHtml = "<div id=\"BlogTitle\">" +
titleString + "</div><br /><div id=\"BlogDate\">"
+ dateString + "</div><br /><br /><div id=\"BlogText\">"
+ textString + "</div>";
Label1.Controls.Add(dynDiv);
}
con.Close();
}
提前致谢!