2014-11-05 83 views
2

我有一個帶有Textboxes的GridView,每行一個。 我需要更改屬性「onkeypress」來驗證密鑰。(ASP.NET)在GridView中更改TextBoxes屬性(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」子句。

非常感謝。

+0

是您的js函數得到任何控制檯錯誤? – Pranav 2014-11-05 15:19:51

+0

不,我不是,但如果我把我的js函數在asp:TextBox with onkeypress =「javascript:return validateFloatKeyPress(this,event);」它工作正常。 – andresfm 2014-11-05 15:27:38

+0

我會看'RowDataBound'事件(根據@andresfm的答案),但是我可以問爲什麼當gridview1.Rows [row.RowIndex]'返回與'row'完全相同的東西嗎? – freefaller 2014-11-05 15:54:28

回答

0

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

而且它正常工作,我覺得:)