Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

c# - Second combobox is populated depending on option from first combobox

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

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

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...