hi
i want to populate country's name in 1st dropdownlist and their states should be placed in the 2nd dropdownlist, if we select any state it should place the name of the capital in the textbox besides that and so on.....
If possible send me code

thank you in advance
raghu

Recommended Answers

All 29 Replies

Simply write an event handler on the SelectedIndex change of the combobox to adjust the item for the second. On the second, have another event handler that sets the textbox value. You can populate a Combo using objects that contain the matching information to go into the text box.
Is this a homework assignment ?

thank you or ypur advice
but i am developing web application using C#,just look at my code which is giving error message...

if (Page.IsPostBack == false)
        {
            SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
            SqlDataAdapter da = new SqlDataAdapter("select countyr_id,countryname from country_master", con);
            DataSet ds1 = new DataSet();
            da.Fill(ds1, "country_master");
            dd1.DataSource = ds1.Tables["country_master"];
            dd1.DataTextField = "countryname";
            dd1.DataValueField = "countyr_id";
            dd1.DataBind();
        }
    }
    protected void dd1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string countryid;
        countryid = dd1.SelectedValue;
        SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
        SqlDataAdapter da1 = new SqlDataAdapter("SELECT stateid,statename FROM countrystate");
        DataSet ds1 = new DataSet();
        da1.Fill(ds1, "countrystate");
        dd2.DataSource = ds1.Tables["countrystate"];
        dd2.DataTextField = "statename";
        dd2.DataValueField = "stateid";
        dd2.DataBind();


    }
    protected void dd2_SelectedIndexChanged(object sender, EventArgs e)
    {
        string stateid;
        stateid = dd2.SelectedValue;
        
    }

If i want to select any country from 1st dropdownlist then,2nd dropdownlist should populate with all the state of that paticular country only and if we select any state from 2nd dropdown then the capital should be placed in text box beside that and so on...

how many tables should we have to create

You need to specify what country to use when you pull the data for the second drop down.

string sql = "SELECT stateid,statename FROM countrystate where country_id='{0}' ";
SqlDataAdapter da1 = new SqlDataAdapter( string.Format(sql,countryid) );

This way it will only contain the states for that country.

i am no geting in that way
will you please explain what are the table are to be created..
please send posr my reply its very important
thank you in advance

Your code should work fine as is, you just need to give the Where Country_id= ... in the query so that it returns the states for that country.

protected void dd1_SelectedIndexChanged(object sender, EventArgs e)
{
string countryid;
countryid = dd1.SelectedValue;
SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
SqlDataAdapter da1 = new SqlDataAdapter(string.Format("SELECT stateid,statename FROM countrystate where country_id='{0}' ",countryid) );
DataSet ds1 = new DataSet();
da1.Fill(ds1, "countrystate");
dd2.DataSource = ds1.Tables["countrystate"];
dd2.DataTextField = "statename";
dd2.DataValueField = "stateid";
dd2.DataBind();
}

I wrote the code as you said, but it showing two error in sqldataAdapter


1.Argument '1': cannot convert from 'string'to 'System.Data.SqlClient.SqlCommand'

2.The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapt er

please sought this problem

ok, I will write the code example, and post it here in the next few minutes.

Attached is a Windows Application project that demos what you are looking for,
I am using my own server (connection string), and it uses two tables. Read the top of the form.c to see my comments.
You should have no problem converting this to asp.

Good luck,
J

thank you very much i will go through that
i will be in touch with you after going through that

hi jerry,sorry to say that the attachment you send to me is not opeaning it showing some error

hi jerry i got your attachment, in that you created tables but,while insering the values it showing some error message as

An explicit value for the identity column in table 'countrymaster88' can only be specified when a column list is used and IDENTITY_INSERT is ON.

where can i get bindingsource components

hi jerry i got your attachement and i build my own application just like yours but i gettin error message, just go through my my coding .

    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
        SqlDataAdapter da = new SqlDataAdapter("select county_id,countryname from country_master88", con);
        DataSet ds1 = new DataSet();
        da.Fill(ds1, "country_master88");
        dd1.DataSource = ds1.Tables["country_master88"];
        dd1.DataTextField = "countryname";
        dd1.DataValueField = "countyr_id";



    }

        protected void dd1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataRowView drv;
        string countryid;
         if (dd1.SelectedValue == null) return;
         if (dd1.SelectedValue is DataRowView)
         {
             drv = (DataRowView)dd1.SelectedValue;
             countryid = drv["country_id"].ToString();
         }
         else
             countryid = dd1.SelectedValue.ToString();
         if (countryid == string.Empty) return;
         string sql = string.Format("SELECT stateid,statename FROM countrystate88 where county_id={0}", countryid);
         SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
         SqlDataAdapter da1 = new SqlDataAdapter(sql, con);
         DataSet ds1 = new DataSet();
         da1.Fill(ds1, "countrystate");
         dd1.DataSource = ds1.Tables["countrystate88"];
         dd2.DataTextField = "statename";
         dd2.DataValueField = "stateid";
         dd2.SelectedIndexChanged(null, null);
    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataRowView drv;
        string countryid;
        string stateid;
        if (dd2.SelectedValue == null) return;
        if (dd2.SelectedValue is DataRowView) 
        {
            drv = (DataRowView)dd2.SelectedValue;
            stateid = drv["stateid"].ToString();
        }
        else
          stateid = dd2.SelectedValue.ToString();
      if (dd1.SelectedValue is DataRowView)
      {
          drv = (DataRowView)dd1.SelectedValue;
          countryid = drv["county_id"].ToString();
      }
      else
          countryid = dd1.SelectedValue.ToString();
      if (countryid == string.Empty || stateid == string.Empty) return;
      string sql = string.Format("SELECT capital FROM countrystate where county_id={0} and stateid={1}", countryid, stateid);
      SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
      con.Open();
      SqlCommand cmd = new SqlCommand(sql, con);
      SqlDataReader rdr = cmd.ExecuteReader();
      rdr.Read();
      t1.Text = rdr[0].ToString();
      con.Close();
    }
}

errors for the above codding is
1. it shows error in the both dropdownlist_selectedchange
near "if (dd2.SelectedValue is DataRowView)"
the message is : The given expression is never of the provided ('System.Data.DataRowView') type

2.next error shows at "drv = (DataRowView)dd1.SelectedValue"
the message Error is: Cannot convert type 'string' to 'System.Data.DataRowView'

3.next error showas at
"dd2.SelectedIndexChanged(null, null)"
the error message is: The event 'System.Web.UI.WebControls.ListControl.SelectedIndexChanged' can only appear on the left hand side of += or -=

and the same errors for all the dropdownlist_selectedindexcanged..


just solve my problem its very urgent

thank you
raghu

rahgu,

What version of c# are you using ?
There are some differences that can cause these problems.

I know you are in dire need of this, but I have to go to work in a few minutes. If you are willing to wait until tonight (California time) I will write it as an ASP application to get rid of the problems you are seeing.

In the mean time, you can modify the code I sent to be used as a Windows Application so you can see how it works. Works flawlessly here.
That may help you get it working in ASP.

I will post the APS version in about 10 hours.

--Jerry

Attached is a simple ASP.net project that demonstrates the double drop-down.
Now this is not real efficient. If this were to be used for a production site, you should cache the information, and use JavaScript or AJAX methods to display the information rather than return to the server side.

Jerry

thanks jerry i am using C# 2.0 version and asp.net 2005

thanks jerry i got through the coding
but the values in dropdown list i am not getting the exact way what i want,i will explain you again that if we select any country from 1stdropdownlist then it should place only selected country's states in the second dropdownlist and so on...
just tell me how many tables should i have to prepare in sql server..

thanku you jerry for your replies, i do consider tha as my best part of my job

hi jerry
for examle if we select usa in first dropdownlist it has to give only all the states of usa in the second dropdownlist and if we select another country from 1st dropdownlist then it has to place only those states in second dropdownlist that paticular country.
thank you

You need two database tables.
One to store the Country ID and Name
The second table to store the Country ID, State Name and State Capital. Simple one to many relationship. Each country has many states, but a state only has one capital.

Populate the first combo with the country, and the value member with the country id. The second combo will contain the state name, and you can place the capital in the value member. If you web site is doing more with the state information then you might want to place a state id in the states table, and use that as the valuemember so that you can pull additional information about the state.

In the demo, you will see the event on the second drop down selected index change uses the country id, and the state id to find the capital value to place into the Label.

--Jerry

hi jerry thanks for your reply
country id in the second table will be more then the country id in the first table just because one country has more number of states, can it possible to populate only paticular country's state in the second dropdownlist by the way you said?
thank you

I think you are struggling with understanding the one to many relationship.
Lets say you have 2 countrys defined in your country_master table. #1=USA, #2=Canada

You can have all USA's states listed in the states table, and you can also have all of the states found in Canada in this very same table. Each row in the states table also has a Country ID column that allows the SQL server to only get the states for a specific Country ID.

Therefore a T-SQL statement of "select * from States where Country_id=1"
will only bring back the states that belong to the USA. If Country_ID were set to 2 in this query, then only Canada's states would be returned.

The purpose of the first drop-down is to get the CountryID that will be used in the query against the States table... As long as you issue the query statement with the "where country_id = nnn", the second dropdown will only contain the states related to that country id.

Hope this Helps,
Jerry

thanks jerry for your reply,i will try the above said example,
and i will keep in you touch with you
raghu

thank you very ,very ,very much jeryy i got through your help, unless you did'nt i can't make it ,you almost saved me from every thing
thank you once again..
if possible give your phone no.so that i can make call

raghu

hi jerry thanks for dropdownlist, but i got another problem regarding updatating a profile of a login member, i created a storedprocedure for login information just look at my codding

CREATE PROCEDURE sp_UserValidation
(
@Username varchar(50),
@UserPassword varchar(20)
) 
AS
IF EXISTS (SELECT UserName FROM LogIn1 WHERE UserName=@Username and UserPassword=@UserPassword)
BEGIN
return 1
END
ELSE
BEGIN
return 0
END
create table login1(username varchar(50)constraint pkusername primary key,userpassword varchar(20) ,
youranswer varchar(40),username varchar(20), useraddress varchar(100),usercity varchar(20),userpostal int,
userphone int,usermobile int,Email varchar(30),website varchar(30))

my problem is i want to update some of login member column but iam not able to update, i wrote some coding for that just go through that,

protected void Button1_Click(object sender, EventArgs e)
    {
SqlConnection con = new SqlConnection("user id=sa;password=vubrain;database=raghu;data source=vubrain4");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
 cmd.CommandText = "Update login1001 Set name = @username1001, pwd = @userpassword1001 where username1001= @username1001";
       cmd.CommandType = CommandType.Text;
       SqlParameter para2;
       SqlParameter para3;
       SqlParameter para4;
       SqlParameter para5;
       //SqlParameter para6;
       SqlParameter para7;
       SqlParameter para8;
       SqlParameter para9;
       para2 = cmd.@Parameters.AddWithValue("loginaddress", tb1.Text);
       para3 = cmd.@Parameters.AddWithValue("logincity", t6.Text);
       para4 = cmd.@Parameters.AddWithValue("loginpostalcode", t7.Text);
       para5 = cmd.@Parameters.AddWithValue("loginphone", t8.Text);
       //para6 = cmd.Parameters.AddWithValue("loginfax", t9.Text);
       para7 = cmd.@Parameters.AddWithValue("loginmobile", t10.Text);
       para8 = cmd.@Parameters.AddWithValue("loginemail", t11.Text);
       para9 = cmd.@Parameters.AddWithValue("loginwebsite", t12.Text);
       int intnum;
       con.Open();
      intnum = cmd.ExecuteNonQuery();
      if (intnum > 0)
      {
        Label2.Text = "updated successfully";

      }
     else
      {
        Label2.Text = "updarted failed";
     }
       con.Close();

please sought out my problem
thank you
raghu

Hi there,

You might want to create a new thread for this question, since it's not related to your other question. That way, more people will look at your question...

ok thanks for informing

How do we convert it into C# web forms?
can you please help me in converting dd1_SelectedIndexChanged for web form.Plz help me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.