向一个空的GridView添加一行

本文关键字:添加 一行 GridView 一个 | 更新日期: 2023-09-27 18:15:14

我想在一个空的gridview中添加一行,我累了下面的代码,但没有运气到目前为止:

        GridViewRow oRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
        TableCell oCell = new TableCell();
        oCell.Text = "XXX";
        oRow.Cells.Add(oCell);
        gvMemberShip.Controls.Add(oRow);

注意:我在Page_Load事件上运行了这个代码。

向一个空的GridView添加一行

我们的方法是扩展GridView。重写CreateChildControls,像这样:

public class CustomGridView : GridView
{
    protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
    {
        int numRows = base.CreateChildControls(dataSource, dataBinding);
        //no data rows created, create empty table
        if (numRows == 0)
        {
            //create table
            Table table = new Table();
            table.ID = this.ID;
            //create a new header row
            GridViewRow row = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
            //convert the exisiting columns into an array and initialize
            DataControlField[] fields = new DataControlField[this.Columns.Count];
            this.Columns.CopyTo(fields, 0);
            this.InitializeRow(row, fields);
            row.TableSection = TableRowSection.TableHeader;
            table.Rows.Add(row);
            this.Controls.Add(table);
        }
        return numRows;
    }
}

重写GridView的CreateChildControls,以便在没有数据显示时向其添加一个空表。

您可以使用GridView的数据源并初始化一个只有1个元素的集合。如果你在Page_Load中这样做,然后调用DataBind(), GridView将显示你的行