因頁面展示需要,如果GridView中的數據不滿一頁時,用空白行補充,自己所用方法爲:
1、在數據源中添加空對象。如我綁定的數據源爲一個對象的list,一頁顯示10條數據,如果list中的對象不夠10個,就爲list添加null對象。
StudyNote sn = new StudyNote();
sn.Name="test";
IList<StudyNote> snlist = new List<StudyNote>();
snlist.Add(sn);
//添加null
int nowCount = snlist.Count;
for (int i = _maxRecord; i > nowCount; i--)
{
snlist.Add(null);
}
2、在gvStudyNote_RowDataBound事件中
private void gvStudyNote_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//添加空行
if (e.Row.DataItem == null)
{
Label lblNoteName = e.Row.FindControl("lblNoteName") as Label;
lblNoteName.Text = " ";//一定要寫 ,否則不會顯示空行,
}
else
{
StudyNote nowSN = e.Row.DataItem as StudyNote;
if (nowStudyNote != null)
{
Label lblNoteName = e.Row.FindControl("lblNoteName") as Label;
lblNoteName.Text = nowSN.name;
}
}
}
//自動編號
if (e.Row.RowIndex != -1)
{
int index = e.Row.RowIndex + 1;
e.Row.Cells[0].Text = index.ToString();
}
}
另外一種在網上找的方法代碼如下,我試了也可以實現,但和有數據的樣式不一樣,只是一個白板,
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (GridView1.PageIndex == GridView1.PageCount-1) //尾頁
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// 計算自動填充的行數
numCount++;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
// 計算完畢,在此添加缺少的行
int toLeft = GridView1.PageSize - numCount;
int numCols = GridView1.Rows[0].Cells.Count;
for (int i = 0; i < toLeft; i++)
{
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
for (int j = 0; j < numCols; j++)
{
TableCell cell = new TableCell();
cell.Text = " ";
row.Cells.Add(cell);
}
GridView1.Controls[0].Controls.AddAt(numCount + 1 + i, row);
}
}
}
}