Click here to Skip to main content
15,893,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is my code.
aspx page:


XML
<%@ 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:
C#
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 give me solution..!
Posted
v2
Comments
You have pasted all the code here. But you should ideally explain the problem you are facing.
Gaurav Agarwal from Jaipur 11-Jun-13 2:49am    
I have created Dynamic text box with this code but want to apply validation control. how can i apply validation controls on dynamically created text boxes?

Try
XML
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);
 
Share this answer
 
Comments
Gaurav Agarwal from Jaipur 11-Jun-13 3:04am    
Where can I apply this validation code?
Abhinav S 11-Jun-13 3:51am    
Try Page_Loaded event or even on a button click.
Gaurav Agarwal from Jaipur 11-Jun-13 3:37am    
Please reply immediately.. it's urgent..
Gaurav Agarwal from Jaipur 11-Jun-13 3:43am    
browser is showing this error message : Object reference not set to an instance of an object.
Dear Gaurav,
Let's say an example textbox1 is your textbox id means, you can add the following code in the Page_load() event.

C#
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;");


Regards,
BlueSathish
 
Share this answer
 
Comments
[no name] 11-Jun-13 8:54am    
yet another way is, just get all the id's which are required with a delimiter and hold these delimited string in a hidden variable, in button click or what so ever, trigger a java script function and get the hidden delimited string and loop through the ids with grid view prefix and check if empty and if so, show a alert .. simple

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900