【问题标题】:(ASP.NET) Change TextBoxes attributes (onkeypress) in GridView(ASP.NET) 在 GridView 中更改 TextBoxes 属性 (onkeypress)
【发布时间】:2014-11-05 14:54:28
【问题描述】:

我有一个内部带有文本框的 GridView,每行一个。 我需要更改属性“onkeypress”来验证键。

<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>

在后面的代码中:

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);");
}

但是当生成文本框时,JavaScript 不起作用。为什么?

我不能在 ASP 部分这样做,因为我希望文本框有不同的 JavaScript 方法,后面的代码中有“if”子句。

非常感谢。

【问题讨论】:

  • 您的 js 函数是否出现控制台错误?
  • 不,我不是,但是如果我将我的 js 函数放在 asp:TextBox 中,并带有 onkeypress="javascript:return validateFloatKeyPress(this, event);"它工作正常。
  • 我会查看RowDataBound 事件(根据@andresfm 的回答),但我能问一下你为什么要做gridview1.Rows[row.RowIndex],而它返回的内容与row 完全相同吗?
  • 嗨@freefaller,谢谢你的提示。是的,你是对的,row 返回的结果与gridview1.Rows[row.RowIndex] 相同。谢谢。

标签: asp.net gridview textbox attributes onkeypress


【解决方案1】:

我在 asp:GridView 中添加了属性 onrowdatabound="GridView1_RowDataBound" 并且似乎工作正常。在后面的代码中,我放了...

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

在后面的代码中:

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);");
    }
}

我认为它可以正常工作:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多