Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8958145
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T15:08:48+00:00 2026-06-15T15:08:48+00:00

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

  • 0

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
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T15:08:49+00:00Added an answer on June 15, 2026 at 3:08 pm

    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

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

this is what i have right now Drawing an RSS feed into the php,
I have an array which has BIG numbers and small numbers in it. I
I have a text area in my form which accepts all possible characters from
I have a reasonable size flat file database of text documents mostly saved in
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have this code to decode numeric html entities to the UTF8 equivalent character.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.