Search code examples
asp.netgridviewtextboxattributesonkeypress

(ASP.NET) Change TextBoxes attributes (onkeypress) in GridView


I have a GridView with Textboxes inside, one for each row. I need change the attribute "onkeypress" to validate keys.

<asp:Table runat="server">
 <asp:TableRow runat="server">
  <asp:TableCell runat="server">
    <asp:GridView ID="gridview_1" DataSourceID="SqlDataSource3" AutoGenerateColumns="false" runat="server">
      <Columns>
        <asp:TemplateField HeaderText="textbox">
          <ItemTemplate>
            <asp:TextBox ID="textbox_1" CssClass="textbox_1" runat="server" Text='<%# Eval("sql_textbox")%>'>
            </asp:TextBox>
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
  </asp:TableCell>
</asp:TableRow>

And in the code behind:

foreach (GridViewRow row in gridview_1.Rows)
{
    TextBox txtbox = ((TextBox)gridview_1.Rows[row.RowIndex].FindControl("textbox_1"));
    txtbox.Attributes.Add("onkeypress","javascript:return validateFloatKeyPress(this, event);");
}

But when textboxes are generated, the JavaScript doesn't work. Why?

I can't do it in the ASP part, because I want the textboxes have different JavaScript methods with "if" clause in the code behind.

Thank you very much.


Solution

  • I put in asp:GridView the attribute onrowdatabound="GridView1_RowDataBound" and seems works properly. In code behind, I put...

    <asp:GridView ID="gridview_1" DataSourceID="SqlDataSource3" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound" runat="server">
    

    In code behind:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.DataItem != null)
        {
          TextBox textBox1 = e.Row.FindControl("textbox_1") as TextBox;
          textBox1.Attributes.Add("onkeypress","javascript:return validateFloatKeyPress(this, event);");
        }
    }
    

    And it works properly, I think :)