2012-03-26 18 views
0

我正在動態生成文本框並將它們添加到佔位符,如下所示。如何訪問動態生成的文本框並應用一些驗證

TextBox txt = new TextBox(); 

txt.ID = "txt" + ds.Tables[0].Rows[i]["id"].ToString(); 
txt.Width = 250; 
txt.ToolTip = ds.Tables[0].Rows[i]["TotalMarks"].ToString(); 
phMemberTextboxes.Controls.Add(txt); 
phMemberTextboxes.Controls.Add(new LiteralControl("\n<br />")); 

我想訪問這些文本框中的值。並且需要檢查文本框的值是否小於工具提示值。如果需要重置文本框。 我該怎麼做?

+0

凡要檢查和重置文本框的值,在客戶端或服務器端? – Coder 2012-03-26 11:49:56

+0

在服務器端,我需要重置這些textboxes.Validation我想在客戶端執行。如果工具提示值比較大,那麼確定還需要顯示一個消息框 – Shah 2012-03-26 11:59:43

回答

1

當U添加動態生成控件佔位符,它們的ID得到改變,你必須先設置控件的客戶端ID在訪問它客戶端:

txt.ClientID = "txt" + ds.Tables[0].Rows[i]["id"].ToString(); 
txt.Attributes.Add("onblur", string.Format("validateControl('{0}');", txt.ClientID); 

然後,在JavaScript:

function validateControl(ctrlId){ 
    var txtCtrl = document.getElementById(ctrlId); 
    int txtVal = txtCtrl.value; 
    // Note that getAttribute doesn't work in IE 6 and requires exact property name 
    var txtMarks = parseInt(txtCtrl.getAttribute("title")); 
    if (txtVal.length < txtMarks.length){ 
     // Reset textbox value and show the message 
     txtCtrl.value = ""; 
     var msg = "Value must be greater than " + txtMarks; 
     alert(msg); 
     txtCtrl.focus(); 
    } 
} 
+0

焦點從控件移開時,調用Javascript的_onblur_。在我的代碼中,如果值小於標記,則重置該值,提醒用戶輸入正確的值並將焦點置於該值上。 – Coder 2012-03-26 12:27:26

+0

剛剛在你的文章中加入.length。 – Pankaj 2012-03-26 12:29:37

+0

獲取屬性時應該是標題。 – Pankaj 2012-03-26 12:42:57

0

設置文本框onclick屬性。

YourButton.Attributes.Add("onclick", "YourJavascriptFunction('" + txt.ClientID + "');"); 
在YourJavascriptFunction

現在

function YourJavascriptFunction(ID) 
{ 
    var txtCtrl = document.getElementById(ctrlId); 
    int txtVal = txtCtrl.value; 
    // Note that getAttribute doesn't work in IE 6 and requires exact property name 
    var txtMarks = parseInt(txtCtrl.getAttribute("title")); 
    if (txtVal.length < txtMarks.length){ 
     // Reset textbox value and show the message 
     txtCtrl.value = ""; 
     var msg = "Value must be greater than " + txtMarks; 
     alert(msg); 
     txtCtrl.focus(); 
    } 

} 

+0

它會檢查驗證當我點擊文本框? – Shah 2012-03-26 11:58:20

+0

您可以根據您的要求選擇任何事件。 – Pankaj 2012-03-26 12:05:20

+0

你想如何執行驗證?我的意思是在哪個事件? – Pankaj 2012-03-26 12:07:50