使用autogeneratecolumn = true创建动态网格视图时,CommandField按顺序排列

时间:2013-11-26 12:07:31

标签: c# asp.net

我正在从后面的代码中动态创建gridview,如下所示

DataTable dt = FromSomesource();

var gridView = new GridView
                   {
                       ID = "Grid_" + grid.GridMasterId
                       DataSource = dt,     
                   };

gridView.RowDeleting += GridRowDeleting;
gridView.RowEditing += GridRowEditing;
//gridView.DataBind(); it doesn't matter if i bind here or later

CommandField cfEdit = new CommandField();

        cfEdit.ButtonType = ButtonType.Button;
        cfEdit.ShowEditButton = true;
        cfEdit.HeaderText = "Edit";
        cfEdit.CausesValidation = false;

        gridView.Columns.Add(cfEdit);

        ExtendedCommandField cfDelete = new ExtendedCommandField();


        cfDelete.ButtonType = ButtonType.Button;
        cfDelete.ShowDeleteButton = true;
        cfDelete.DeleteConfirmationRequired = true;
        cfDelete.DeleteConfirmationText = "Are you sure you want to remove this item?"; 
        cfDelete.HeaderText = "Delete";
        cfDelete.CausesValidation = false;
        gridView.Columns.Add(cfDelete);

gridView.DataBind();

问题是CommandField是第一列,而我希望它是水平排列的最后一列。我可以通过一些简单的方式完成它而无需删除现有列并在gridview中重新添加它

1 个答案:

答案 0 :(得分:0)

那么,你想要什么具体的?
如果您想要使用autogeneratecolumns=false动态创建gridview,则需要将其直接设置为false,因为此属性的默认值为true,因此在这种情况下,您必须更改此代码

DataTable dt = FromSomesource();

var gridView = new GridView
               {
                   ID = "Grid_" + grid.GridMasterId
                   DataSource = dt,     
                   AutoGenerateColumns = false
               };

gridView.RowDeleting += GridRowDeleting;
gridView.RowEditing += GridRowEditing;

/*
    this loop for adding data columns to gridview
*/

CommandField cfEdit = new CommandField();    
cfEdit.ButtonType = ButtonType.Button;
cfEdit.ShowEditButton = true;
cfEdit.HeaderText = "Edit";
cfEdit.CausesValidation = false;
gridView.Columns.Add(cfEdit);


gridView.DataBind();

如果您未将AutoGenerateColumns设置为false,则可以尝试将AutoGenerateEditColumn设置为true并删除您创建的代码并手动添加CommandField

<强>更新 尝试下一个代码

DataTable dt = FromSomesource();

var gridView = new GridView
               {
                   ID = "Grid_" + grid.GridMasterId
                   DataSource = dt,     
                   AutoGenerateEditColumn = true
               };

gridView.RowDeleting += GridRowDeleting;
gridView.RowEditing += GridRowEditing;
gridView.DataBind();