在有些開發實踐中有時候為了頁面美觀的需要需要將GridView填充成固定行數的表格下面這個方法實現了這種填充的功能此方法可以處理自動產生列和模版列注意由於時間關系沒有實現對完全空白數據的填充呵呵如果需要可以自己添加哈)!
C#
<%@ Page Language=
C#
%>
<!DOCTYPE html PUBLIC
//W
C//DTD XHTML
Transitional//EN
transitional
dtd
>
<script runat=
server
>
// 計算數據
完全可以從數據看取得
ICollection CreateDataSourceByXianhuiMeng()
{
System
Data
DataTable dt = new System
Data
DataTable();
System
Data
DataRow dr;
dt
Columns
Add(new System
Data
DataColumn(
學生班級
typeof(System
String)));
dt
Columns
Add(new System
Data
DataColumn(
學生姓名
typeof(System
String)));
dt
Columns
Add(new System
Data
DataColumn(
語文
typeof(System
Decimal)));
dt
Columns
Add(new System
Data
DataColumn(
數學
typeof(System
Decimal)));
dt
Columns
Add(new System
Data
DataColumn(
英語
typeof(System
Decimal)));
dt
Columns
Add(new System
Data
DataColumn(
計算機
typeof(System
Decimal)));
for (int i =
; i <
; i++)
{
System
Random rd = new System
Random(Environment
TickCount * i); ;
dr = dt
NewRow();
dr[
] =
班級
+ i
ToString();
dr[
] =
【孟子E章】
+ i
ToString();
dr[
] = System
Math
Round(rd
NextDouble() *
);
dr[
] = System
Math
Round(rd
NextDouble() *
);
dr[
] = System
Math
Round(rd
NextDouble() *
);
dr[
] = System
Math
Round(rd
NextDouble() *
);
dt
Rows
Add(dr);
}
System
Data
DataView dv = new System
Data
DataView(dt);
return dv;
}
// 設置每頁顯示的行數
int TotalRowCount =
;
// 自動填充的行數
int numCount =
;
protected void Page_Load(object sender
EventArgs e)
{
if (!Page
IsPostBack)
{
GridView
DataSource = CreateDataSourceByXianhuiMeng();
GridView
DataBind();
}
}
protected void GridView
_RowDataBound(object sender
GridViewRowEventArgs e)
{
if (e
Row
RowType == DataControlRowType
DataRow)
{
// 計算自動填充的行數
numCount++;
}
if (e
Row
RowType == DataControlRowType
Footer)
{
// 計算完畢
在此添加缺少的行
int toLeft = TotalRowCount
numCount;
int numCols = GridView
Rows[
]
Cells
Count;
for (int i =
; i < toLeft; i++)
{
GridViewRow row = new GridViewRow(
DataControlRowType
EmptyDataRow
DataControlRowState
Normal);
for (int j =
; j < numCols; j++)
{
TableCell cell = new TableCell();
cell
Text =
;
row
Cells
Add(cell);
}
GridView
Controls[
]
Controls
AddAt(numCount +
+ i
row);
}
}
}
</script>
<html xmlns=
>
<head runat=
server
>
<title>自動填充固定行數的 GridView</title>
</head>
<body>
<form id=
form
runat=
server
>
<asp:GridView ID=
GridView
runat=
server
OnRowDataBound=
GridView
_RowDataBound
Font
Size=
px
CellPadding=
>
<HeaderStyle BackColor=
#EDEDED
/>
<Columns>
<asp:TemplateField HeaderText=
模版列
>
<ItemTemplate>
<%#Eval(
學生姓名
) %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
From:http://tw.wingwit.com/Article/program/net/201311/12482.html