我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindDetails();
}
public void BindDetails()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Designation", typeof(string)));
dt.Columns.Add(new DataColumn("Address", typeof(string)));
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
if (i % 2 == 0)
{
dr["Name"] = "Ram";
dr["Designation"] = "Manager";
dr["Address"] = "Nerul";
}
else
{
dr["Name"] = "Shyam";
dr["Designation"] = "CEO";
dr["Address"] = "Vashi";
}
dt.Rows.Add(dr);
}
grdDetails.DataSource = dt;
grdDetails.DataBind();
}
protected void grdDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnEdit = (Button)e.Row.FindControl("btnEdit");
//btnEdit.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference((Control)sender, "value$" + e.Row.RowIndex.ToString()));
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference((Control)sender, "value$" + e.Row.RowIndex.ToString()));
}
}
protected void grdDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "value")
{
txtName.Text = grdDetails.Rows[Convert.ToInt32(e.CommandArgument)].Cells[0].Text;
txtDesignation.Text = grdDetails.Rows[Convert.ToInt32(e.CommandArgument)].Cells[1].Text;
txtAddress.Text = grdDetails.Rows[Convert.ToInt32(e.CommandArgument)].Cells[2].Text;
}
}
请给出解决方案。
答案 0 :(得分:1)
如果我没记错,AttributeCollection
中没有ViewState
。然后,您需要在每个回发上注册click事件,而不仅仅是数据绑定。因此,请尝试使用RowCreated
代替RowDataBound
。
protected void grdDetails_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnEdit = (Button)e.Row.FindControl("btnEdit");
//btnEdit.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference((Control)sender, "value$" + e.Row.RowIndex.ToString()));
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference((Control)sender, "value$" + e.Row.RowIndex.ToString()));
}
}