我创建了一个动态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 控件,代码就可以工作。我没有使用任何母版页。