Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add all elements of array to datagridview rows except one

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
like image 903
Amanda_Panda Avatar asked Dec 05 '12 21:12

Amanda_Panda


1 Answers

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

like image 172
Jeremy Thompson Avatar answered Sep 28 '22 01:09

Jeremy Thompson