在RowDataBound期间无法通过id找到控件

时间:2015-04-30 03:02:13

标签: c# gridview findcontrol rowdatabound

我创建了一个动态网格视图,并希望将rowdatabound和SelectedIndexChanged分配给gridview。

下面是我的代码 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
 }

我在RowDataBound的查找控件总是返回null值。如果我在HTML上创建gridview控件,代码正在工作。我不使用任何母版页。

1 个答案:

答案 0 :(得分:0)

buildGridView();在GET建立。但是,当你有交易后回复。它实际上再次处理asp生命周期。你可以把你的datalist放到viewstate并删除!ispostback()因此,当你回发时,你的数据网格实际上不是构建因此是null。