0

I want to add a row inside an empty gridview, i tired the following code but no luck so far:

        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);

Note: i ran this code on Page_Load Event.

2 Answers 2

2

the way we did it is to extend the GridView. Override the CreateChildControls, with something like:

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;
    }
}

Overrides the GridView' CreateChildControls to Add an Empty table to it when there is no data to display.

1
  • This code produce an error for me "There is no suitable method to override", and second i honestly don't understand the purpose of this code so if somebody could explain. Thanks.
    – ykh
    Nov 22, 2011 at 10:17
0

You could use the DataSource of the GridView and initialize with a collection with only 1 element. If you do this in your Page_Load and then call DataBind() the GridView will show your row.

1
  • I don't want this in the datasource, what i am trying to achieve here is an Insert Row Capability.
    – ykh
    Nov 21, 2011 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.