如何访问动态生成的文本框并应用一些验证

时间:2012-03-26 11:29:57

标签: asp.net

我正在动态生成文本框并将它们添加到占位符中,如下所示。

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

我想访问这些文本框中的值。并需要检查文本框值是否小于工具提示值。如果是这样,需要重置文本框。 我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

当你向占位符添加动态生成的控件时,他们的ID会被更改,你必须先设置控件的ClientID才能在客户端访问它:

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

答案 1 :(得分:0)

设置TextBox 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();
    }

}