iftee
iftee

Reputation: 369

How to add a row in asp.net grid view

So far I have done this, I am not sure whether this is right or wrong

public partial class _Default : System.Web.UI.Page 
{
    Label l = new Label();
    GridView gv = new GridView();
    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            GridViewRow gvr = new GridViewRow(i, i, DataControlRowType.DataRow, DataControlRowState.Normal);
            gvr.Controls.Add(l);
            gv. (what to do here)
        }

        this.Controls.Add(gv);

    }
}

please help

Upvotes: 0

Views: 703

Answers (2)

Sheetal Inani
Sheetal Inani

Reputation: 128

The DataGrid fires the RowCreate event when a new row is created. Collapse

//OnRowCreated="GridView3_RowCreated" 

protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
{

  //When a child checkbox is unchecked then the header checkbox will also be unchecked.
  if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == 
    DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
  {

    CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkselect");
    CheckBox chkBxHeader = (CheckBox)this.GridView3.HeaderRow.FindControl("chkHeader");
    chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(
        this,'{0}');", chkBxHeader.ClientID);
  }
}

Upvotes: 0

John Sheehan
John Sheehan

Reputation: 78152

gv.Rows.Add(gvr);

If you're starting with an empty GridView, an easier way to dynamically create x rows is to create a dummy list and then set it to the data source:

var list = new List<string>(10); // replace 10 with number of empty rows you want
// for loop to add X items to the list
gv.DataSource = list;
gv.DataBind();

If you are doing this, I'd recommend doing it with a Repeater. It's a lot easier to manage.

Upvotes: 5

Related Questions