如何在asp.net网格视图中添加一行

时间:2009-08-14 18:39:39

标签: asp.net gridview

到目前为止,我已经这样做了,我不确定这是对还是错

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

    }
}

请帮助

2 个答案:

答案 0 :(得分:5)

gv.Rows.Add(gvr);

如果您从一个空的GridView开始,动态创建x行的一种更简单的方法是创建一个虚拟列表,然后将其设置为数据源:

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

如果您这样做,我建议您使用中继器。管理起来要容易得多。

答案 1 :(得分:0)

创建新行时,DataGrid会触发RowCreate事件。  崩

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