Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I have two combobox's. The first combobox has all the states and the second would show the districts of the selected state. Note that the options are coming from a .txt file.

So in this case the "states.txt" file is formed like "state code;state".

Ex:

01;New York

02;New Jersey

...

The state combobox is working fine, below is the code used:

List<string> States = File.ReadAllLines("states.txt").ToList();

foreach(string Line in States)
{
     string[] state_element = Line.Split(';');
     combo_states.Items.Add(state_element[1]);
}

The problem now is having the second combobox show the districts of the selected state.

The "district.txt" file is formed like "state code; district code; district".

Ex:

01;01;Manhattan

01;02;Brooklyn

...

Also note that I am not using any form of database, so no SQL or anything, just c# language.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

As I understood you are losing the Id of the state when you just put its name in the Combobox.

set your first combobox to display the 'Name' and have 'Id' as value:

combo_states.ValueMember = "Id";
combo_states.DisplayMember = "Name";

foreach(string Line in States)
{
     string[] state_element = Line.Split(';');
     combo_states.Items.Add(new { Id = state_element [0], Name = state_element[1]});
}

Now in your combobox's on SelectedValueChange event you can access the Id of the state like:

string id = combo_states.SelectedValue;

and having districts like:

var districts = File.ReadAllLines("district.txt")
.Select(x => 
     { 
         string split = x.Split(';');
         return new {StateId = split[0], DistrictId = split[1], DistrictName = split[1]}
     };

Then:

string id = combo_states.SelectedValue;
district_combo.ValueMember = "DistrictId";
district_combo.DisplayMember = "DistrictName";
foreach(var item in districts.Where(d => d.StateId == id))
{
      district_combo.Items.Add(item);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...