简体   繁体   中英

can't find control by id during RowDataBound

i created a dynamic gridview and want to assigned the rowdatabound and SelectedIndexChanged to the gridview.

below is my code HTML

<div id="divGridView" runat="server"></div>

C#

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
        buildGridView();
    }
}

public void buildGridView()
{
    GridView gvSample = new GridView();
    gvSample.ID = "gvSample";
    gvSample.AutoGenerateColumns = false;
    gvSample.RowDataBound += gvSample_RowDataBound;
    gvSample.SelectedIndexChanged += gvSample_SelectedIndexChanged;

    DataTable dt = new DataTable();
    DataColumn dc = new DataColumn();

    BoundField BoundField1 = new BoundField();
    BoundField1.DataField = "BoundField11";

    gvSample.Columns.Add(BoundField1);

    if (dt.Columns.Count == 0)
    {
         dt.Columns.Add("BoundField11", typeof(string));
    }

    DataRow NewRow = dt.NewRow();
    NewRow[0] = "sample data";
    dt.Rows.Add(NewRow);

    gvSample.DataSource = dt;
    gvSample.DataBind();
    divGridView.Controls.Add(gvSample);
}

protected void gvSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         GridView gvSample = (GridView)Page.FindControl("gvSample");
         e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvSample, "Select$" + e.Row.RowIndex);
         e.Row.Style["cursor"] = "pointer";
     }
 }

 protected void gvSample_SelectedIndexChanged(object sender, EventArgs e)
 {
      // do something
 }

my find control at RowDataBound always return null value. the code is working if i create the gridview control at HTML. im NOT using any master page.

buildGridView(); is build at GET. but, when you have transaction post back. it actually process again on asp life cycle. you may put ur datalist to viewstate and removed !ispostback() therefore, when you postback, your datagrid actually is not build therefore is null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM