Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi I am new to asp.net I made a Registration form and i need to bind Country and state in my application ie When I select the country I need the state related to be displayed.I have the details of it in SQL server.
Also Need to select the dob and to get the age automatically pleas help me.Thanks in Advance

What I have tried:

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


namespace Test
{
    public partial class RegistrationForm : System.Web.UI.Page
    {
        //string CS = ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString);


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindAll();
            }
        }

        public void BindAll()
        {
            cn.Open();
            SqlCommand cmd = new SqlCommand("select CountryName,CounID from Country_details", cn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DDlCountry.DataSource = dt;
            DDlCountry.DataTextField = "CountryName";
            DDlCountry.DataValueField = "CounID";
            DDlCountry.DataBind();
            cn.Close();
        }
        public void Bind_ddlState()
        {
            cn.Open();

            SqlCommand cmd = new SqlCommand("select StateName,CounID from State_details where CounID='" + DDlCountry.SelectedValue + "'", cn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            Ddlstate.DataSource = dt;
            Ddlstate.DataTextField = "StateName";
            Ddlstate.DataValueField = "CounID";
            Ddlstate.DataBind();
            Ddlstate.Enabled = true;
            cn.Close();
        }




        protected void txtDOB_SelectionChanged(object sender, EventArgs e)
        {

        }




        protected void Button1_Click1(object sender, EventArgs e)
        {
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO RegistrationDetails1 (Name, Department,Salary,Doj,Dob, Age,Country,State,Phone,Email) VALUES ('" + txtname.Text + "','" + txtDept.Text + "','" + txtSalary.Text + "','" + txtDOJ.Text + "','" + txtDOB.Text + "','" + txtAge.Text + "','" + DDlCountry.Text + "','" + Ddlstate.Text + "','" + txtPhone.Text + "','" + TxtEmail.Text + "','" + txtPin.Text + "' )", cn);
                cmd.ExecuteNonQuery();
                cn.Close();
            }

        }


        protected void Button2_Click1(object sender, EventArgs e)
        {
            this.ClearCachedClientID();

        }



        protected void cal()
        {

            if (Calendar2.Visible == false)
            {
                Calendar2.Visible = true;

            }
            else
            {
                Calendar2.Visible = false;
            }
            if (Calendar1.Visible == false)
            {
                Calendar1.Visible = true;
            }
            else
            {
                Calendar1.Visible = false;
            }
        }

        protected void Calendar2_SelectionChanged(object sender, EventArgs e)
        {
            txtDOB.Text = Convert.ToString(Calendar1.SelectedDate);
        }

        protected void txtDOB_TextChanged(object sender, EventArgs e)
        {

        }

        protected void DDlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        protected void ddltest_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bind_ddlState();
        }




    }
}
Posted
Updated 8-Jan-17 22:58pm
Comments
DamithSL 9-Jan-17 2:51am    
You need to explain which part of your code is not working and what are the exceptions you get etc..
Member 12605293 9-Jan-17 3:01am    
Hi Damith.
The country is binding properly,but the state is not binding when i select a particular country.

The Calendar Control of Date of birth is not show the age.

One big problem is that you concatenate directly the values to SQL statement. This leaves you wide open to SQL injection and conversion problems etc. The correct way is to use SqlParameter Class (System.Data.SqlClient)[^]

Another thing is that you don't dispose the objects so resources are not correctly freed. Also you should add proper error handling to handle common exceptions.

For examples have a look at Properly executing database operations[^]

What comes to the calendar, it looks like you're taking the value from Calendar1 in Calendar2_SelectionChanged. Is this intentional?
 
Share this answer
 
v2
Comments
Member 12605293 9-Jan-17 3:43am    
Hi
Thanks for your reply.Im not geeting you.Can you make the code here ?for calendar,The question is "When I select the Date of Birth,The age of the person should fill the age txtbox automatically"I need the code for this if the above is incorrect.
Wendelius 9-Jan-17 3:59am    
The comments are related on how you build the SQL statements, so you should have a look a them and fix the potential problems.

About the calendar I wrote a question if you are getting the date from correct control or not

What comes to state, it looks like you're not investigating if this is postback. Try modifying the code

if (!IsPostBack) {
Bind_ddlState();
}
Member 12605293 9-Jan-17 4:41am    
Hi Mika
Thanks it is working good for binding state now.But Don't understand the problem in case of calendar.
Wendelius 9-Jan-17 4:46am    
As said you take the value from Calendar1 control in Calendar2 event handler. Is that the correct control? Also check the postback
Member 12605293 9-Jan-17 6:07am    
Hi Yes I have doubt in Validation.Not even a single validation is working .
Quote:
The country is binding properly,but the state is not binding when i select a particular country.

there are few things you need to note, one is AutoPostBack should be true for the DDlCountry as below and you need to give the selected index change event name correctly
ASP.NET
<asp:DropDownList id="DDlCountry" runat="server" AutoPostBack="true" OnSelectIndexChanged="DDlCountry_SelectedIndexChanged"/>

now change the DDlCountry_SelectedIndexChanged as below
protected void DDlCountry_SelectedIndexChanged(object sender, EventArgs e)
      {
        Bind_ddlState();
      }
 
Share this answer
 
1. Call Bind_ddlState() from DDlCountry_SelectedIndexChanged (..) event but method was called from different event.
2. Set AutoPostback="true" for DDLCountry from design view or else from properties window.
 
Share this answer
 
Comments
Member 12605293 9-Jan-17 5:32am    
Hi Yes I have done the same,but it has shows only the first value of both country and state.
Ramesh Kumar Barik 9-Jan-17 7:38am    
Issue : SqlCommand cmd = new SqlCommand("select StateName,CounID from State_details where CounID='" + DDlCountry.SelectedValue + "'", cn);

The query which u have mentioned it selects the StateName with COuntryID from state_Details table. But you should select StateName with StateID for StateDropdownlist for which the stateID will selected for StateDropdownlist.

Here the CounID is always same with parameter which you use in where condition.

1. So please change the query Statename with StateID for Statedropdownlist.

Ex: SqlCommand cmd = new SqlCommand("select StateName,StateID from State_details where CounID='" + DDlCountry.SelectedValue + "'", cn);

2. Ddlstate.DataValueField = "StateID";
Member 12605293 9-Jan-17 8:33am    
Hi Thanks for the reply.I have used the same column name of CounID in both the tables .
Ramesh Kumar Barik 9-Jan-17 9:52am    
Thanks.
One Question.
How you relate your parent table (Country_details) and child table (State_details).

Is there any OwnID for State_details?
If yes, then select that ID and bind the same for StateDropDownlist.
Member 12605293 9-Jan-17 23:46pm    
Hi
I have a common Id's for both the table(CounID)
ASP.NET
<pre>%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegForm1.aspx.cs" Inherits="Test.RegistrationForm" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
    <style>
        input[type=label] {
    border: 2px solid Blue;
    border-radius: 2px;
}

        input[type=text] {
    border: 2px solid red;
    border-radius: 4px;
}
   body {
    background-color: lightblue;
}
        </style>
    <title>Database</title>
    <script type="text/javascript">

        
        function Valid1(e, t) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert("Invalid ");
            }
        }
        function Valid2(e, r) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 47 && charCode < 91) )
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert("Invalid ");
            }
        }
        function Valid2(e, r) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 47 && charCode < 91))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert("Invalid ");
            }
        }
        function Valid4(e, r) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 41 && charCode < 58))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert("Invalid ");
            }
        }
        function IsValidEmail(email) {
            var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            return expr.test(email);
        };
        function ValidateEmail() {
            var email = document.getElementById("txtEmail").value;
            if (!IsValidEmail(email)) {
                alert("Invalid email address.");
            }
            else {
                alert("Valid email address.");
            }
        }
        function ageCount() {
            var date1 = new Date();
            var dob= document.getElementById("dob").value;
            var date2=new Date(dob);
            var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/; //Regex to validate date format (dd/mm/yyyy)
            if (pattern.test(dob)) {
                var y1 = date1.getFullYear(); //getting current year
                var y2 = date2.getFullYear(); //getting dob year
                var age = y1 - y2; //calculating age 
                document.write("Age : " + age);
                return true;
            } else {
                alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
                return false;
            }
        function onlyAlphabets(e, t) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert("Invaild");
            }
        }
        
        
        
        

 </script>
</head>
    
<body>
    <form id="form1" runat="server">
        <div>
            <table border="0">
                
                <tr>
                    <th colspan="3">Registration
                    </th>
                </tr>
                <tr>
                    <td style="width: 362px">Name
                    </td>
                    
                    <td>
                        <asp:TextBox ID="txtname" runat="server" onkeypress ="Valid1(e, t) " ControlToValidate="txtname"/>
                        
                        
                    </td>
                    <td>
                         </td>
                    <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="" ControlToValidate="txtname"
                            runat="server" />
                    </td>
                </tr>
                <tr>
                    <td style="width: 362px">Department
                    </td>
                    <td>
                        <asp:TextBox ID="txtDept" runat="server" />
                        <input type="text" onkeypress="return Valid2(event,this);" /> 
                    </td>
                    <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="" ControlToValidate="txtDept"
                            runat="server" />
                    </td>
                </tr>
                <tr>
                    <td style="width: 362px">Salary
                    </td>
                    <td>
                        <asp:TextBox ID="txtSalary" runat="server" onkeypress="return Valid4(event,this);" />
                    </td>
                    <td style="width: 662px">
                        <asp:CompareValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="txtSalary" runat="server" />
                    </td>
                </tr>

                <tr>
                    <td style="width: 362px">DOJ
                    </td>
                    <td>
                        <asp:TextBox ID ="txtDOJ" runat="server" />
                    </td>
                                   
                <td>
                        <asp:Calendar ID="Calendar1" runat="server" onkeypress="return ValidateDate (sender, args)" BackColor="White" BorderColor="#999999" CellPadding="4" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" Height="180px" Width="200px"  >
                       </asp:Calendar>
                    </td>
                    <td style="height: 1px; width: 662px;">
                        <%--<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="txtDOJ" runat="server" />--%>
                    </td>
                </tr>
                <tr>
                    <td style="width: 362px">DOB
                    </td>
                    <td>
                        <asp:TextBox ID ="txtDOB" runat="server" OnTextChanged="txtDOB_TextChanged1" />
                    </td>
                    <td>
                        <asp:Calendar ID="Calendar2" runat="server" onclick="return ageCount" BackColor="White" BorderColor="#999999" CellPadding="4" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" Height="180px" Width="200px" >
                       </asp:Calendar>
                        
                    </td>
                    <td style="width: 662px">
                       <%-- <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="txtDOB" runat="server" />--%>
                    </td>
                </tr>
                <tr>
                    <td style="width: 362px">Age
                    </td>
                    <td>
                        <asp:TextBox ID="txtAge" onkeypress="return Valid4(event,this)" runat="server" />
                    </td>
                    <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="txtAge" runat="server" />
                    </td>
                </tr>

                <tr>
                    <td style="width: 362px">Country
                    </td>
                    <td>
                        <asp:DropDownList ID="DDlCountry" runat="server" AutoPostBack="true" Height="21px" Width="122px" 
                            OnSelectedIndexChanged="DDlCountry_SelectedIndexChanged"></asp:DropDownList>
                        
                    </td>
                  <%--  <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="DDlCountry" runat="server" />
                    </td>--%>

                </tr>
                <tr>
                    <td style="width: 362px">State
                    </td>
                    <td>
                        <asp:DropDownList ID="Ddlstate" runat="server" onkeypress="return onlyAlphabets(event,this);" Height="21px" Width="122px"></asp:DropDownList>
                    </td>
                    <%--<td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="Ddlstate" runat="server" />
                    </td>--%>
                </tr>
                <tr>
                    <td style="width: 362px">Phone
                    </td>
                    <td>
                        <asp:TextBox ID="txtPhone" runat="server" onkeypress="return Valid4(event,this)" Height="21px" Width="122px" />
                    </td>
                    <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="txtPhone" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td style="width: 362px">Email
                    </td>
                    <td>
                        <asp:TextBox ID="TxtEmail" runat="server" onclick = "ValidateEmail()" Height="21px" Width="122px" />
                    </td>
                    <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="TxtEmail" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td>PinCode
                    </td>
                    <td>
                        <asp:TextBox ID="txtPin" runat="server" onkeypress="return Valid4(event,this)"  Height="21px" Width="122px" />
                    </td>
                    <td style="width: 662px">
                        <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor=""
                            ControlToValidate="txtPin" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td></td>
                    

                </tr>

                <tr>
                    <td style="width: 362px"></td>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />
                        <asp:Button ID="Button2" runat="server" Text="Cancel" OnClick="Button2_Click1" />
                    </td>
                    <td style="width: 6px"></td>
                </tr>

            </table>
        </div>
    </form>
    <script>
        //validate()
        //alert("Name Field can not be blank")
    </script>
</body>
</html>
 
Share this answer
 

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