6

I'm reading a text file line by line, and inserting it into an array.

I then have this list called custIndex, which contains certain indices, indices of the items array that I'm testing to see if they are valid codes. (for example, custIndex[0]=7, so I check the value in items[7-1] to see if its valid, in the two dictionaries I have here). Then, if there's an invalid code, I add the line (the items array) to dataGridView1.

The thing is, some of the columns in dataGridView1 are Combo Box Columns, so the user can select a correct value. When I try adding the items array, I get an exception: "The following exception occurred in the DataGridView: System.ArgumentException: DataGridViewComboBoxCell value is not valid."

I know the combo box was added correctly with the correct data source, since if I just add a few items in the items array to the dataGridView1, like just items[0], the combo box shows up fine and there's no exception thrown. I guess the problem is when I try adding the incorrect value in the items array to the dataGridView1 row.

I'm not sure how to deal with this. Is there a way I can add all of the items in items except for that value? Or can I add the value from items and have it show up in the combo box cell, along with the populated drop down items?

if(choosenFile.Contains("Cust"))
{
    var lines = File.ReadAllLines(path+"\\"+ choosenFile);

    foreach (string line in lines)
    {
        errorCounter = 0;
        string[] items = line.Split('\t').ToArray();

        for (int i = 0; i <custIndex.Count; i++)
        {
            int index = custIndex[i];
            /*Get the state and country codes from the files using the correct indices*/
            Globals.Code = items[index - 1].ToUpper();

            if (!CountryList.ContainsKey(Globals.Code) && !StateList.ContainsKey(Globals.Code))
            {
                errorCounter++;

                dataGridView1.Rows.Add(items);
            }
        }//inner for

        if (errorCounter == 0)
            dataGridView2.Rows.Add(items);

    }//inner for each

}//if file is a customer file
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
Amanda_Panda
  • 1,156
  • 4
  • 26
  • 68
  • 1
    Why not put the records into a List, then remove bad records from the list (or use LINQ to select only the good records into a new Array/List)? – Trisped Dec 05 '12 at 21:55
  • Is there a way to add the value from the items array to a combobox cell? It works if I set the offending value in the array to string.empty,but it seems like I should also be able to show the value in the combo box. – Amanda_Panda Dec 05 '12 at 22:49
  • I think so, but it has been a while since I have tried. You might also try creating a new column type and use the default ComboBox with the ability to enter custom values into the text box portion turned on. Then just set the text of the ComboBox to the value you are getting. – Trisped Dec 05 '12 at 22:55

1 Answers1

6

Say your text file contains:

Australia PNG, India Africa
Austria Bali Indonisia
France England,Scotland,Ireland Greenland
Germany Bahama Hawaii
Greece Columbia,Mexico,Peru Argentina
New Zealand Russia USA

And lets say your DataGridView is setup with 3 columns, the 2nd being a combobox.

enter image description here

When you populate the grid and incorrectly populate the combobox column you will get the error.

The way to solve it is by "handling/declaring explicitly" the DataError event and more importantly populating the combobox column correctly.

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    //Cancelling doesn't make a difference, specifying the event avoids the prompt 
    e.Cancel = true;
}

private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    e.Cancel = true;
}

So imagine the 2nd column contained a dropdownlist of countries and the 1st & 3rd column contained text fields.

For the 1st and 3rd columns they are just strings so I create a class to represent each row:

public class CountryData
{
    public string FirstCountry { get; set; }
    public string ThirdCountry { get; set; }
}

For the 2nd column "Countries" combobox cell's I have created a separate class because I will bind it to the 2nd columns datasource.

public class MultiCountryData
{
    public string[] SeceondCountryOption { get; set; }
}

Populating the grid with combobox columns and the like as shown here: https://stackoverflow.com/a/1292847/495455 is not good practice. You want to separate your business logic from your presentation for a more encapsulated, polymorphic and abstract approach that will ease unit testing and maintenance. Hence the DataBinding.

Here is the code:

namespace BusLogic
{
public class ProcessFiles
{

internal List<CountryData> CountryDataList = new List<CountryData>();
internal List<MultiCountryData> MultiCountryDataList = new List<MultiCountryData>();

internal void foo(string path,string choosenFile)
{
    var custIndex = new List<int>();
    //if (choosenFile.Contains("Cust"))
    //{
        var lines = File.ReadAllLines(path + "\\" + choosenFile);
        foreach (string line in lines)
        {
            int errorCounter = 0;
            string[] items = line.Split('\t');

            //Put all your logic back here...

            if (errorCounter == 0)
            {
                var countryData = new CountryData()
                                      {
                                          FirstCountry = items[0],
                                          ThirdCountry = items[2]
                                      };
                countryDataList.Add(countryData);

                multiCountryDataList.Add( new MultiCountryData() { SeceondCountryOption = items[1].Split(',')});

            }
        //}
      }

}
}

In your presentation project here is the button click code:

 imports BusLogic;
 private void button1_Click(object sender, EventArgs e)
 {
     var pf = new ProcessFiles();
     pf.foo(@"C:\temp","countries.txt"); 
     dataGridView2.AutoGenerateColumns = false;
     dataGridView2.DataSource = pf.CountryDataList;
     multiCountryDataBindingSource.DataSource = pf.MultiCountryDataList;      
 }

I set dataGridView2.AutoGenerateColumns = false; because I have added the 3 columns during design time; 1st text column, 2nd combobox column and 3rd text column.

The trick with binding the 2nd combobox column is a BindingSource. In design time > right click on the DataGridView > choose Edit Columns > select the second column > choose DataSource > click Add Project DataSource > choose Object > then tick the multiCountry class and click Finish.

enter image description here

enter image description here

Also set the 1st column's DataPropertyName to FirstCountry and the 3rd column's DataPropertyName to ThirdCountry, so when you bind the data the mapping is done automatically.

enter image description here

Finally, dont forget to set the BindingSource's DataMember property to the multiCountry class's SeceondCountryOption member.

enter image description here

Here is a code demo http://temp-share.com/show/HKdPSzU1A

Community
  • 1
  • 1
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • Is there a way to add the second column in your text file as the default, showing value in the combo box? – Amanda_Panda Dec 08 '12 at 00:08
  • So, for example, PNG would be the default value being shown for the first row column box? Or just have it showing in that cell? – Amanda_Panda Dec 08 '12 at 00:08
  • Thats easy, if you want PNG to be the default value for the 1st rows' combobox, simply set `dataGridView2.Rows[0].Cells[1].Value = "PNG";` in your code after you bind the DataSources. – Jeremy Thompson Dec 08 '12 at 01:07
  • 1
    Oh, I was just giving an example :) Hard coding it is easy. Thanks, I will take a look at this when I get a chance! – Amanda_Panda Dec 08 '12 at 05:51
  • Jeremy: Does your solution also work if the columns aren't defined in the designer? What if the number and name of columns isn't determined until run time? – Amanda_Panda Dec 09 '12 at 06:19
  • All the Design-Time code is produced in the Form.Designer.cs file, so if you need to do this at runtime use that code file as an example. Also I'll edit the code to show you how to separate the code from the presentation. – Jeremy Thompson Dec 09 '12 at 07:48
  • 3
    +1 for all the detailed screenshots - definitely a crazy level of detail. – Jon Peterson Dec 12 '12 at 17:26