最近项目中需要gridview动态生成行数,最后解决办法如下:
ICollection CreateDataSource()
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("AAA", typeof(System.String)));
dt.Columns.Add(new System.Data.DataColumn("BBB", typeof(System.String)));
dt.Columns.Add(new System.Data.DataColumn("CCC", typeof(System.Decimal)));
dt.Columns.Add(new System.Data.DataColumn("DDD", typeof(System.Decimal)));
for (int i = 0; i < 10; i++)
{
System.Random rd = new System.Random(Environment.TickCount * i); ;
dr = dt.NewRow();
dr[0] = "TEST" + i.ToString();
dr[1] = i.ToString();
dt.Rows.Add(dr);
}
System.Data.DataView dv = new System.Data.DataView(dt);
return dv;
}
int TotalRowCount = 12;
// 自动填充行数
int numCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
numCount++;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
int toLeft = TotalRowCount - 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);
}
}
}