Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Winform DataGridView with a pair of cascaded comboboxes

Posted on 2009-06-29
9
Medium Priority
?
898 Views
Last Modified: 2012-06-21
I am trying to set up a 2 comboboxes in a DataGridView, one with a State, the second holding a list of counties for that particular state.  I have bound the state combobox to an array of state names, and that works fine.  I have county column bound to a filtered collection of counties.  I update the filtered list in the 'RowEnter' and the 'CellValueChanged" event.  This seems to work fine, as I can select a state, and the county list displays the correct list of counties.  However, when I try and go to the next row(which is a newly created row), I get the following error message:
System.ArgumentException: DataGridViewComboBoxCell value is not valid.

The form load looks like this
        private void frmEditor_Load(object sender, EventArgs e)
        {
           /* omit code to fetch list of states and counties */
            colState.DataSource = oStates;
            colState.ValueMember = "StateFipsCode";
            colState.DisplayMember = "State";

             colCounty.DataSource = oFiltered;
             colCounty.DisplayMember = "County";
             colCounty.ValueMember = "CountyFipsCode";
        }

        // function called on RowEnter and CellValueChanged event (in state column)
        void UpdateFilter()
        {
            oFiltered.Clear();
            int nStateFips = SafeObjToInt(dgFarms.Rows[e.RowIndex].Cells[1].Value);
            // adding a blank county row did not help anything
            //oFiltered.Add(new FarmSimData.cCountyFips("", -1, "", -1));
            for (int i = 0; i <= oCountyByState.GetUpperBound(0); i++)
                if (nStateFips == (int)oCountyByState[i][0].StateFipsCode)
                {
                    for (int j = 0; j <= oCountyByState[i].GetUpperBound(0); j++)
                        oFiltered.Add(oCountyByState[i][j]);
                    break;
                }
        }

Thanks for any help
0
Comment
Question by:bnonnemann
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
9 Comments
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 24737517
Is a default "State" selected when you enter go the newly created row?
0
 

Author Comment

by:bnonnemann
ID: 24737603
Nothing specific was selected for the State
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 24739077
That sounds like the problem then... I recommend that you build in a test to see if the State has a valid selected index before you try to use it. I would do it something like this...
// assumes C# 9.0 ... you'll need to adjust the syntax if you're using an earlier version.
// function called on RowEnter and CellValueChanged event (in state column) 
void UpdateFilter()
{
    if (!string.IsNullOrEmpty(dgFarms.Rows[e.RowIndex].Cells[1].Value))
    {
        var intCheck = default(int);
        int.TryParse(dgFarms.Rows[e.RowIndex].Cells[1].Value, intCheck);
 
        if (intCheck > 0)
        {
            oFiltered.Clear();
            int nStateFips = SafeObjToInt(dgFarms.Rows[e.RowIndex].Cells[1].Value);
            // adding a blank county row did not help anything
            //oFiltered.Add(new FarmSimData.cCountyFips("", -1, "", -1));
            for (int i = 0; i <= oCountyByState.GetUpperBound(0); i++)
            {
                if (nStateFips == (int)oCountyByState[i][0].StateFipsCode)
                {
                        for (int j = 0; j <= oCountyByState[i].GetUpperBound(0); j++)
                            oFiltered.Add(oCountyByState[i][j]);
                        break;
                }
            }
        }
    }
}

Open in new window

0
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 24739126
A couple of syntax updates (my bad)...

if (!string.IsNullOrEmpty(dgFarms.Rows[e.RowIndex].Cells[1].Value))
SHOULD BE
if (!string.IsNullOrEmpty((string)dgFarms.Rows[e.RowIndex].Cells[1].Value))


int.TryParse(dgFarms.Rows[e.RowIndex].Cells[1].Value, intCheck);
SHOULD BE
int.TryParse((string)dgFarms.Rows[e.RowIndex].Cells[1].Value, intCheck);

Try those and see what you get.
0
 

Author Comment

by:bnonnemann
ID: 24757587
It turns out that your suggestion was only part of the solution.   The problem comes up when you wwitch between rows that have different states.  For example, say in the first row you select the state 'Alabama', and then pick 'Butler' county.  You then go to the next row, and you select 'Illinois', and the 'Grundy'as the county.  So far, so good -- but when you return to the first line, the county list reverts back to those for Alabama, and the second row (containing the Illinois data) now displays 'Greene' county -- the county in Alabama that matches the FIPS code for 'Grundy' county in Illinois.  When you switch back to the row with Illinois as the state, then 'Grundy' county reappears in the county column.  Argh!   I'm going to try to see if making the county fips codes unique helps things, but I have the sinking feeling that the end result will be blank county entries when you switch states.

Thanks for you help so far!!
0
 

Author Comment

by:bnonnemann
ID: 24757649
As I expected, changing the county fips codes to be unique (by combining state and county codes into a composite value) results in county columns going blank in rows whose state does not make the state in the current row.
0
 
LVL 28

Accepted Solution

by:
Ark earned 500 total points
ID: 24758378
This is because your filtered list applies to all rows. Try to populate countly combo directly (without datasource) in EditingControlShowing event like
cboCountly.Items.Clear();
//.............
   for (int j = 0; j <= oCountyByState[i].GetUpperBound(0); j++)
          cboCountly.Items.Add(oCountyByState[i][j]);
                        break;

BTW, unique code is a good idea to save table data and initialy populating it (you can use CellFormatting event for this)
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 24762543
Sorry; was away from the Internet yesterday.
I agree with Ark's logic. That's actually the technique I would have used for my own needs.
0
 

Author Closing Comment

by:bnonnemann
ID: 31597993
Sorry, was away from the office for a while -- this suggestion works just fine.  Thanks!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question