0

我创建了一个动态gridview,并希望将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 的查找控件总是返回空值。如果我在 HTML 中创建 gridview 控件,代码就可以工作。我没有使用任何母版页。

4

1 回答 1

0

构建网格视图();在 GET 构建。但是,当您有事务回发时。它实际上在asp生命周期中再次处理。您可以将您的数据列表放入视图状态并删除 !ispostback() 因此,当您回发时,您的数据网格实际上并未构建,因此为空。

于 2015-04-30T03:10:46.053 回答