如何在动态文本框中应用验证? [英] How can i apply validation on dynamic text box?

查看:90
本文介绍了如何在动态文本框中应用验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码。

aspx页面:





here is my code.
aspx page:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnAddAddress" runat="server" Text="Add a New Address" OnClick="btnAddAddress_Click" />
        <asp:Button ID="btnSave" runat="server" Text="Save These Addresses" OnClick="btnSave_Click" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <asp:Panel ID="pnlAddressContainer" runat="server">
        </asp:Panel>
        <br />
    </div>
    </form>
</body>
</html>





cs page:



cs page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class Default3 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
    static DataTable dtabl;
    DataColumn no;
    DataColumn address;
    protected void Page_PreLoad(object sender, EventArgs e)
    {
        // Use ViewState to store the number of the addresses.
        if (ViewState["AddressCount"] == null)
        {
            ViewState["AddressCount"] = 0;
        }

        // Get the the number of the addresses.
        int addresscount = (int)ViewState["AddressCount"];

        // Iterat adding addresses input component.
        for (int i = 0; i < addresscount; i++)
        {
            if (addresscount == 3)
            {
                btnAddAddress.Visible = false;
            }
            AddAdress((i + 1).ToString());
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            dtabl = new DataTable();
            no = new DataColumn("no", Type.GetType("System.Int32"));
            address = new DataColumn("address", typeof(string));

            dtabl.Columns.Add("no");
            dtabl.Columns.Add("address");
            
        }

    }
    
    protected void btnAddAddress_Click(object sender, EventArgs e)
    {
        
        if (ViewState["AddressCount"] != null)
        {
            int btncount =  (int)ViewState["AddressCount"];
            //dynamic validator = new RequiredFieldValidator();

            // Add a new component to pnlAddressContainer.
            if (btncount == 4)
            {
                btnAddAddress.Visible = false;
            }
            else
            {
                AddAdress((btncount + 1).ToString());
                ViewState["AddressCount"] = btncount + 1;
                //validator.ID = ds.Tables(0).Rows(i).Item(0) + "_Validator";
                //validator.ControlToValidate = myTextBox.ID;
                //validator.ErrorMessage = ds.Tables(0).Rows(i).Item(2) + " required ";
                //validator.Display = ValidatorDisplay.Dynamic;
                //this.TextBoxControlPlaceHolder.Controls.Add(validator);
            }
        }
        else
        {
            Response.Write("ERROR");
            Response.End();
        }
    }

    
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int addresscount = (int)ViewState["AddressCount"];

        // Display all the addresses on the page.
        // This is an imitation that we update these addresses into database.
        for (int i = 0; i < addresscount; i++)
        {
            TextBox tb = pnlAddressContainer.FindControl("TextBox" + (i + 1).ToString()) as TextBox;
            string address = tb.Text == "" ? "Empty" : tb.Text;
            Response.Write("Address" + (i + 1).ToString() + " is " + address + ".<br />");
            string Add1 = address.ToString();
            
            DataRow row = dtabl.NewRow();
            //dtabl.Rows[i][0] = Session["slctans"].ToString();
            //dtabl.Rows[i+1][0] = i;
            //dtabl.Rows[i+1][1] = address.ToString();
            row[0] = i.ToString();
            row[1] = address;

            dtabl.Rows.Add(row);
            ViewState["P" + (i + 1)] = address;

        }
        Session["dtabl"] = dtabl;
        if (Session["dtabl"] != null)
        {
            //string p1, p2, p3, p4;
            dtabl = (DataTable)Session["dtabl"];
            //SqlDataAdapter da = new SqlDataAdapter();
            //DataSet ds = new DataSet();
            //da.Fill(dtabl);
            
            GridView1.DataSource = dtabl;
            GridView1.DataBind();

            if (ViewState["P1"] != null)
            {
                ViewState["P1"] = ViewState["P1"].ToString();
            }
            else
            {
                ViewState["P1"] = "";
            }
            if (ViewState["P2"] != null)
            {
                ViewState["P2"] = ViewState["P2"].ToString();
            }
            else
            {
                ViewState["P2"] = "";
            }
            if (ViewState["P3"] != null)
            {
                ViewState["P3"] = ViewState["P3"].ToString();
            }
            else
            {
                ViewState["P3"] = "";
            }
            if (ViewState["P4"] != null)
            {
                ViewState["P4"] = ViewState["P4"].ToString();
            }
            else
            {
                ViewState["P4"] = "";
            }

           // SqlConnection con = new SqlConnection("initial catalog=UTS003/SQLEXPRESS;data source=Test; integrated security=yes");
            SqlCommand com = new SqlCommand("Insert into Phone values('"+ViewState["P1"]+"','"+ViewState["P4"]+"','"+ViewState["P4"]+"','"+ViewState["P4"]+"')", con);
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
            Response.Write("<script>alert('inserted...')</script>");

            //if (dtabl.Rows[0] != null)
            //{
            //    p1 = dtabl.Rows[0][1].ToString();
            //}
           // else
            //{
            //    p1 = "";
            //}
            //int p1=dtabl.Rows[i][1].ToString()

        }

        // Clear the ViewState.
        ViewState["AddressCount"] = null;
    }
    public void Insert()
    {
        dtabl = (DataTable)Session["dtabl"];
        if (dtabl != null)
            {
                for (int i = 0; i < dtabl.Rows.Count; i++)
                {

                }
            }
    }
    protected void AddAdress(string id)
    {
        // Label to display address No.
        Label lb = new Label();
        lb.Text = "Address" + id + ": ";

        // TextBox for inputting the address.
        TextBox tb = new TextBox();
        tb.ID = "TextBox" + id;

        if (id != "1")
        {
            // Have a try on the code without this condition.
            // We will get a odd behaviour on this after clicking Save button.
            tb.Text = Request.Form[tb.ID];
        }

        // Button to check the Address.
        // Also to illustrate how to bind events to a dynamic control.
        Button btn = new Button();
        btn.Text = "Check";
        btn.ID = "Button" + id;

        // Bind event using += operator.
        btn.Click += new EventHandler(ClickEvent);

        Literal lt = new Literal() { Text = "<br />" };

        // Add these controls to pnlAddressContainer as a component.
        pnlAddressContainer.Controls.Add(lb);
        pnlAddressContainer.Controls.Add(tb);
        pnlAddressContainer.Controls.Add(btn);
        pnlAddressContainer.Controls.Add(lt);
    }

    protected void ClickEvent(object sender, EventArgs e)
    {
        // Get button instance from sender.
        Button btn = sender as Button;

        // Get TextBox instance and its value via FindControl() method.
        TextBox tb = pnlAddressContainer.FindControl(btn.ID.Replace("Button", "TextBox")) as TextBox;
        string address = tb.Text == "" ? "Empty" : tb.Text;

        // Alert a msg to show the address in the corresponding TextBox.
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<script type=\"text/javascript\">");
        sb.Append("alert(\"Address" + btn.ID.Replace("Button", "") + " is " + address + ".\");");
        sb.Append("</script>");

        if (!ClientScript.IsClientScriptBlockRegistered(this.GetType(), "AlertClick"))
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "AlertClick", sb.ToString());
        }
    }
}



plz给我解决方案..!


plz give me solution..!

推荐答案

尝试

Try
RequiredFieldValidator rfv1 = new RequiredFieldValidator();

rfv1.ID = "rfv1";
rfv1.ControlToValidate = tb.ID;
rfv1.Text = "please enter a value for tb1";


rfv1.Validate();

Response.Write("<br>Page.IsValid: " + Page.IsValid);


亲爱的Gaurav,

假设示例textbox1是你的textbox id意思,你可以在Page_load()事件中添加以下代码。



Dear Gaurav,
Let's say an example textbox1 is your textbox id means, you can add the following code in the Page_load() event.

RequiredFieldValidator rfvtxt = new RequiredFieldValidator();
rfvtxt.ControlToValidate = textbox1.ID;
rfvtxt.ErrorMessage = "Please enter the values";
rfvtxt.ToolTip = "Please enter the Comments";
rfvtxt.SetFocusOnError = true;
rfvtxt.Text = "*";
rfvtxt.EnableClientScript = true;
rfvtxt.Attributes.Add("style", "color: Red;");





问候,

BlueSathish



Regards,
BlueSathish


这篇关于如何在动态文本框中应用验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆