我有 gridview 的模板字段,如下所示:
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBonus" runat="server"></asp:TextBox>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</EditItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
当我参加gv_RowUpdating
活动时,我想通过 findcontrol 获取已编辑字段的值。
为此,我使用以下代码:
`TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");`
但是每次它在我调试代码时都向我展示了null
价值。txtUname
可能是什么问题?
完整事件代码:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");
float bonus = float.Parse(gv.DataKeys[e.RowIndex].Values["bonus"].ToString());
try
{
cmd = new SqlCommand("update emp set empName=@eName");
cmd.parameters.AddParametersWithValue("@eName",txtUname.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
编辑
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='"+eName+"'",con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}