以下是我如何填充GridView控件。我是從代碼隱藏,而不是從.aspx前端執行此操作。下面是什麼,我有一個非常簡化版本:RowDataBound事件中的一行與Gridview的分頁機制衝突
private void UpdateGridView()
{
DataTable temptable = new DataTable();
DataColumn idcol = new DataColumn();
DataColumn titlecol = new DataColumn();
idcol.ColumnName = "ID";
titlecol.ColumnName = "Title";
temptable.Columns.Add(idcol);
temptable.Columns.Add(titlecol);
...(get data from the database, store it as variable "x")...
DataRow tempdr;
tempdr[idcol] = x.ID;
tempdr[titlecol] = x.Title;
temptable.Rows.Add(tempdr);
GridView1.DataSource = temptable;
GridView1.DataBind();
}
要處理分頁GridView的「AllowPaging」設置爲true,和我有以下事件處理程序:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
UpdateGridView();
}
而這個偉大工程!
不過,我也有RowDataBound事件處理程序:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; //hide the ID
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes["onclick"] = "location.href='newsindex.aspx?NewsArticleID=" + e.Row.Cells[0].Text + "'";
}
}
我在這裏的目標是讓行本身是點擊,並導致帶有等於該行的ID查詢字符串的另一頁。我需要ID列中的值,以便在創建行時可以訪問它,以便我可以將ID添加到鏈接的QueryString中。但我不希望ID列可見,所以我在行中添加了:e.Row.Cells[0].Visible = false;
這樣做會破壞分頁功能。頁碼不再顯示。如果我註釋掉這一行,它就可以工作,但ID在GridView中可見。
1)爲什麼? 2)我可以做些什麼來獲得相同的功能,但可能的變化最少?