Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my windows form application, there are two combo boxes. 1st one is for brand code and 2nd one is for brand name. I load all data to both combo boxes at form load. When I select one brand code from the code list, relevant brand name is displayed it's combo box (2nd). It is ok.
But I want to other way round also, as when selects brand name brand code should be displayed in it's combo box.
I use Microsoft access Database.
How to implement both processes at one interface?

What I have tried:

//form load event

private void Brands_Load(object sender, EventArgs e)
{
    try
    {
        con.Open();
        OleDbDataReader reader = null;
		OleDbCommand cmd = new OleDbCommand("Select * From Brand", con);
        reader = cmd.ExecuteReader();               
                  
        while (reader.Read())
        {

            cmbbCode.Items.Add(reader["BCODE"].ToString());
            cmbbName.Items.Add(reader["BNAME"].ToString());
        }
                
        con.Close();

    }
    catch (Exception ex)
    {
        MessageBox.Show("error " + ex);
    }
}

//cmbBcode change value event

		private void cmbbCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                String Bcode = cmbbCode.Text.ToString();
                con.Open();
                OleDbDataReader reader = null;
                OleDbCommand cmd = new OleDbCommand("Select BNAME From Brand Where BCODE = '" + Bcode + "'", con);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    String Name = reader["BNAME"].ToString();
                    cmbbName.Text = Name;
                }
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("error " + ex);
            }
        }
        }
Posted
Updated 8-Feb-18 23:45pm
Comments
Richard MacCutchan 9-Feb-18 5:11am    
Just add the same code as above but swapping the combo boxes.
Hashain Fernando 9-Feb-18 5:25am    
cannot, because when i am calling cmbbCode_SelectedIndexChanged method (it calls when i select a value from brand code combo box), cmbbName_SelectedIndexChanged method also calling.

And there is an exception. (connection is not closed).
Hashain Fernando 9-Feb-18 5:46am    
Below exception occured.

System.InvalidOperationException: The connection was not closed. The connection's current state is open.
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at AutoSpa_Xpress.Brands.cmbbName_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\hashainf\documents\visual studio 2010\Projects\AutoSpa Xpress\AutoSpa Xpress\Brands.cs:line 211

1 solution

I wouldn't do it like that. Instead don't use a DateReader, use a DataAdapter, and use the .NET built in code to access the data.
This code uses SQL Server instead of OleDb, but it's the same for your DB - I happen to have SSMS open so it's easier for me to play with SQL Server at the moment:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    DataTable dt = new DataTable();
    using (SqlDataAdapter da = new SqlDataAdapter("Select BCODE, BNAME FROM Brand", con))
        {
        da.Fill(dt);
        cmbbCode.DataSource = dt;
        cmbbCode.DisplayMember = "BCODE";
        cmbbName.DataSource = dt;
        cmbbName.DisplayMember = "BNAME";
        cmbbCode.SelectedIndex = 0;
        }
    }
This reads the data from your DB, and tells each ComboBox to display a different value from the same record.
Then set them both to handle the SelectedIndexChanged event via the same handler:
private void cmbBoth_SelectedIndexChanged(object sender, EventArgs e)
    {
    ComboBox cb = sender as ComboBox;
    if (cb != null && cmbbCode.DataSource != null && cmbbName.DataSource != null)
        {
        int index = cb.SelectedIndex;
        if (index >= 0)
            {
            if (cmbbCode.SelectedIndex != index) cmbbCode.SelectedIndex = index;
            if (cmbbName.SelectedIndex != index) cmbbName.SelectedIndex = index;
            }
        }
    }
The handler gets the new index from whichever ComboBox the user just changed, and sets it to them both. The null checks make sure that both are loaded already (or you'd get an error that the index is out of range) and the "is it the same index?" checks make sure that we don;t get an infinite loop of index changes!
Try it: it's a lot simpler to use than you might think, and it lets the system handle everything for you, which is much cleaner than your solution.
 
Share this answer
 
Comments
Hashain Fernando 10-Feb-18 0:24am    
Thanks for your help.
OriginalGriff 10-Feb-18 1:59am    
You're welcome!
Hashain Fernando 14-Feb-18 23:51pm    
Please explain what is the difference between OleDbDataReader and OleDbDataAdaptor
OriginalGriff 15-Feb-18 3:20am    
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...

A very quick search **using your question as the search term** gave 23,000 hits:
https://www.google.co.uk/search?q=what+is+the+difference+between+OleDbDataReader+and+OleDbDataAdaptor&oq=what+is+the+difference+between+OleDbDataReader+and+OleDbDataAdaptor&aqs=chrome..69i57&sourceid=chrome&ie=UTF-8

In future, please try to do at least basic research yourself, and not waste your time or ours.

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