给gridview动态绑定数据列及命令列
/// <summary> /// 绑定生成GridView
/// </summary>
/// <param name="gdv">要绑定的GridView</param>
/// <param name="dtblDataSource">GridView的数据源</param>
/// <param name="strDataKey">GridView的DataKeyNames</param>
public static void GridViewBind(GridView gdv, DataTable dtblDataSource, string strDataKey)
...{
gdv.Columns.Clear();
gdv.AutoGenerateColumns = false;
gdv.DataSource = dtblDataSource;
gdv.DataKeyNames = new string[] ...{ strDataKey };
for (int i = 0; i < dtblDataSource.Columns.Count; i++) //绑定普通数据列
...{
BoundField bfColumn = new BoundField();
bfColumn.DataField = dtblDataSource.Columns[i].ColumnName;
bfColumn.HeaderText = dtblDataSource.Columns[i].Caption;
gdv.Columns.Add(bfColumn);
}
gdv.Columns[1].Visible = false;
CommandField cfModify = new CommandField(); //绑定命令列
cfModify.ButtonType = ButtonType.Button;
cfModify.SelectText = "修改";
cfModify.ShowSelectButton = true;
gdv.Columns.Add(cfModify);
gdv.DataBind();
}