Question How to correctly made two depending Comboboxes?

Beginnerprog

New member
Joined
Oct 29, 2017
Messages
1
Programming Experience
Beginner
I have a problem with two dependent Combobox. I want to do the dependent Comboboxes. When selecting an area in combobox1, a free taxi located in this area should be displayed on combobox2. I found this video on YouTube and tried to use the code in this video https://www.youtube.com/watch?v=n0J_VH6Rh4A. But when I finished, it does not work correctly and shows an error in the code: System.ArgumentException: Binding to a new value member is impossible!

here an error picture
error02.jpg

Please help how to fix this?
:confusion:

Here the code:

usingMySql.Data.MySqlClient;

namespace check_disp
{
publicpartialclass check2 :Form
{
MySqlConnection connect =newMySqlConnection("datasource=localhost;port=3306;initial catalog=test;username=root;password=");
MySqlCommand cmnd;
MySqlDataAdapter adapt;
DataTable tbl;


public check2()
{
InitializeComponent();
}

privatevoid check2_Load(object sender,EventArgs e)
{
string query ="SELECT `id_loc`, `locations` FROM `local`";
fillcmbo
(comboBox1, query,"locations","id_loc");
comboBox1_SelectedIndexChanged
(null,null);
}

publicvoid fillcmbo(ComboBox combo,string query,string displayMember,string valueMember)
{
cmnd
=newMySqlCommand(query, connect);
adapt
=newMySqlDataAdapter(cmnd);
tbl
=newDataTable();
adapt
.Fill(tbl);
combo
.DataSource= tbl;
combo
.DisplayMember= displayMember;
combo
.ValueMember= valueMember;//showing error here - **Binding to a new value member is impossible**
}

privatevoid comboBox1_SelectedIndexChanged(object sender,EventArgs e)
{
int value;
Int32.TryParse(comboBox1.SelectedValue.ToString(),out value);
string query ="SELECT `id_csl` `id_car`, `id_status`, `id_location` FROM `car_stat_loc` WHERE id_status=1 AND `id_location`="+ value;
fillcmbo
(comboBox2, query,"id_car","id_csl");
}
}
}
 
Firstly, when posting code snippets, please don't post as HTML. The colour-coding helps but you still lose indenting. Please post as plain text inside appropriate formatting tags, i.e.

[xcode=c#]your code here[/xcode]

That will add colour-coding automatically and it will also maintain indenting, which makes code far easier to read.

As for your issue, the first thing to do is to get rid of this line:
comboBox1_SelectedIndexChanged(null,null);

That does nothing useful.

Secondly, you should ALWAYS set the DataSource last when binding. I believe that that is what's causing your issue. Set the DisplayMember and ValueMember first, then set the DataSource.

Also, there's no point declaring your 'cmnd', 'adapt' and 'tbl' variables at the class level. They are only used in one method and you create new objects every time so they should be local variables in that method.
 

Latest posts

Back
Top Bottom