none
How to show first two fields in a comma separated file in C# RRS feed

  • Question

  •  Hi, I have the following text file.

    47891,"Jim Musumeci","Finance","Trainee",1,15
    47892,"Andrew Walker","Accounting","Supervisor",1,25
    47893,"John Summey","Marketing","Clerk",1,17
    47894,"Travis John","Operation","Clerk",1,17
    47895,"John Walker","Accounting","Employee Lead",1,18

    Now I need to show the first two fields in a list box
    and show all the fields in a different form in six text boxes
    corresponding the id number (the first field).

    I am using the following code to get each of the lines from the file in the list box.

    I am not sure how to get individual parsed fields so as to show the id and name only
    in the list box and all the fields in text boxes in another form.

    I appreciate any help. Thanks

    CODE:   

    try
          {
    
                //Declare a variable to hold a employee data
                string employeeData;
    
                //Declare a StreamReader variable
                StreamReader inputfile;
    
                //Open the file and get a Streamrader object.
                inputfile = File.OpenText("employee.txt");
    
                //Clear anything currently in the ListBox.
                employeesListBox.Items.Clear();
    
                //Read the file's contents.
    
                while (!inputfile.EndOfStream)
                {
                   //Get employee data
                   employeeData = inputfile.ReadLine();
    
                   //Add the employeeData 
                   employeesListBox.Items.Add(employeeData);
                }
                //Close the file.
                inputfile.Close();
             }
          catch (Exception ex)
          {
                //Display an error message.
                MessageBox.Show(ex.Message);
          }



    Sunday, December 10, 2017 10:30 PM

Answers

  • Hello gamaz123,

    you should set the label as public so that you could access the label text from current form.

    And your code should be like below.

                EmployeeDetailsForm empdetForm = new EmployeeDetailsForm();
    
                empdetForm.employeeDetailsLabel.Text = value;
    
                empdetForm.ShowDialog();

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by gamaz123 Tuesday, December 12, 2017 5:42 PM
    Tuesday, December 12, 2017 1:46 AM
    Moderator

All replies

  • From a previous post of yours, I remembered that you have an Employee class defined. You should make use of that to make this a bit easier. First, see this StackOverflow post about how to read your file into a List<Employee>:

    https://stackoverflow.com/questions/26790477/read-csv-to-list-of-objects

    Now, all you have to do is databind your List to your ListBox and to your TextBoxes. The TextBoxes are easy:

    BindingSource bs = new BindingSource();
    bs.DataSource = MyEmployeeList;
    
    this.txtID.DataBindings.Add("Text", bs, "IDNumber");
    this.txtName.DataBindings.Add("Text", bs, "Name");
    // etc....
    

    For setting the DataSource for the ListBox, you will need to add an additional property to your Employee class (and you can populate that property when you read in the data from the CSV file).

    Then, set the DataSource like this:

    this.listBox1.DataSource = bs;
    this.listBox1.DisplayMember = "IDandName"; // your newly created Employee class property
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, December 11, 2017 12:29 AM
    Moderator
  • https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-parse-strings-using-string-split

    you could just use the Split(',').

    and then you can use an index on the array.

    string item1 = words[0];

    string item2 = words[1];

    Monday, December 11, 2017 12:49 AM
  • Hello gamaz123,

    Linq also is a good choice for you, try to use Skip and Take method.

     ...
    //Get employee data
    employeeData = inputfile.ReadLine();
    
    var IdandName=String.Join(",",employeeData.Split(',').Take(2));
    //Add the employeeData 
    listBox1.Items.Add(IdandName);
    ...

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 11, 2017 2:05 AM
    Moderator
  • Thanks for the generous help. I am trying all the above methods in my test system to see which one works best for my situation. 

    I just tried your method. With that, I am getting the following output in the listbox.

    47891,"Jim Musumeci"
    47892,"Andrew Walker"
    47893,"John Summey"
    47894,"Travis John"
    47895,"John Walker"

    However, is there any way to display the above data without the double quotes around each of the name? How does one extract the rest of the fields (without the double quotes where those exists) to be utilized in individual text boxes? Thanks.

    Monday, December 11, 2017 2:33 AM
  • Hello gamaz123,

    >>is there any way to display the above data without the double quotes around each of the name

    Try the replace method.

     //Get employee data
                        employeeData = inputfile.ReadLine().Replace("\"", "");
    
                        var IdandName=String.Join(",",employeeData.Split(',').Take(2));
                        //Add the employeeData 
    
                        listBox1.Items.Add(IdandName);

    >>How does one extract the rest of the fields (without the double quotes where those exists) to be utilized in individual text boxes

    It has a lot of ways to achieve it. The simple way is using replace method again.

       var te= employeeData.Replace(IdandName+",", "");
    
                        textBox1.Text = te;

    Or

      var te= String.Join(",", employeeData.Split(',').Skip(2).Take(4));
    
                 
                        textBox1.Text = te;

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 11, 2017 3:19 AM
    Moderator
  • OK 
    Once I have the listbox population with the idnum and name, if I choose one of the items from the list it should open an employee detail form showing rest of the fields for that row.
    On the employee details form I need  the text box to be assigned to the variable te.
    var te = employeeData.Replace(IdandName + ",", "");

    However in the new employee detail form do I need to again loop through the file to find the corresponding value of te?

     Thanks in advance.

    Here is the code so far:

     private void getEmployeeButton_Click(object sender, EventArgs e)
          {
          try
          {
    
                //Declare a variable to hold a employee data
                string employeeData;
    
                //Declare a StreamReader variable
                StreamReader inputfile;
    
                //Open the file and get a Streamrader object.
                inputfile = File.OpenText("employee.txt");
    
                //Clear anything currently in the ListBox.
                employeesListBox.Items.Clear();
    
                //Read the file's contents.
    
                while (!inputfile.EndOfStream)
                {
                   //Get employee data
                   //employeeData = inputfile.ReadLine();
                   employeeData = inputfile.ReadLine().Replace("\"", "");
    
                   var IdandName = String.Join(",", employeeData.Split(',').Take(2));
    
                   
                   //Add the employeeData 
                   employeesListBox.Items.Add(IdandName);
                  // var te = employeeData.Replace(IdandName + ",", "");
                 
                }
                //Close the file.
                inputfile.Close();
             }
          catch (Exception ex)
          {
                //Display an error message.
                MessageBox.Show(ex.Message);
          }
    
          }
    
          private void employeesListBox_SelectedIndexChanged(object sender, EventArgs e)
          {
             // Get the currently selected item in the ListBox.
             string curItem = employeesListBox.SelectedItem.ToString();
    
             //HERE I NEED TO HAVE THE CODE TO ASSIGN THE TE TO THE TEXT BOX// var te = employeeData.Replace(IdandName + ",", "");
             //Create an instance of EmployeeDetailsForm
             EmployeeDetailsForm empdetForm = new EmployeeDetailsForm();
             
             empdetForm.ShowDialog();
           
          }

    Monday, December 11, 2017 5:11 AM
  • You need to take advantage of the Employee class, as I showed in my reply (along with the info in the StackOverflow link). Instead of dealing with a lot of strings, you are then dealing with Employee instances, with all its available properties. This will make it quite easy to databind both your ListBox and the TextBoxes in your EmployeeDetailsForm (as I also showed in my reply).

    Have you tried it? Do you have questions about it?


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, December 11, 2017 6:00 AM
    Moderator
  • Yes, I  have checked the StackOverflow link and found it somewhat complex. So I took the easier route here though I totally agree that this one is heavy on string. 

    Regards.

    Monday, December 11, 2017 6:24 AM
  • Hello gamaz123,

    You could define a Dictionary object as field to store the data from file.

      Dictionary<string, string> dict = new Dictionary<string, string>();
    
            private void button1_Click(object sender, EventArgs e)
            {
                 ...
                     //Read the file's contents.
                    while (!inputfile.EndOfStream)
                    {
                        //Get employee data
                        employeeData = inputfile.ReadLine().Replace("\"", "");
    
                        var IdandName=String.Join(",",employeeData.Split(',').Take(2));
                        //Add the employeeData 
                       
                       //var te= String.Join(",", employeeData.Split(',').Skip(2).Take(4));            
                       // textBox1.Text = te;
                        listBox1.Items.Add(IdandName);
    
                        dict.Add(IdandName, employeeData);
                    }
                    //Close the file.
                    inputfile.Close();
                }
               ...
            }      
            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
               
                    // Get the currently selected item in the ListBox.
                    string curItem = listBox1.SelectedItem.ToString();
    
                string value = dict[curItem].Replace(curItem + ",", "");
                textBox1.Text = value;
                //HERE I NEED TO HAVE THE CODE TO ASSIGN THE TE TO THE TEXT BOX// var te = employeeData.Replace(IdandName + ",", "");
                //Create an instance of EmployeeDetailsForm
    
    
                //EmployeeDetailsForm empdetForm = new EmployeeDetailsForm();
    
                //empdetForm.ShowDialog();
    
            }

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 11, 2017 7:22 AM
    Moderator
  • Yes, I  have checked the StackOverflow link and found it somewhat complex. So I took the easier route here though I totally agree that this one is heavy on string. 

    Complex? Wow,  I thought it was fairly easy. And, I really like how all the parsing of the data would be done in the Employee class itself (which is where it belongs, in my opinion).

    And, since you can databind the ListBox to the List<Employee> (and perhaps a BindingList<Employee> might be better), it makes it really easy to take the instance of an Employee class chosen from the ListBox selection and pass that one instance to your EmployeesDetailForm. Otherwise, you're going to have to retrieve that data all over again, since with the code you're currently going with you're only splitting out the ID and the Name.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, December 11, 2017 2:49 PM
    Moderator
  • Thanks for the help.

    I just tried the code and am getting the following error:

    The name 'employeeDetailsLabel' does not exist in the current context. It was my fault as it is a label and not a text box. Also the label is not on the form where the list box exists rather employee details form which opens up with the corresponding employee details after clicking on a particular employee from the list box. 

    Do you have any further thoughts on this? Thanks.

    Dictionary<string, string> dict = new Dictionary<string, string>();
    
    private void getEmployeeButton_Click(object sender, EventArgs e)
          {
          try
          {
    
                //Declare a variable to hold a employee data
                string employeeData;
    
                //Declare a StreamReader variable
                StreamReader inputfile;
    
                //Open the file and get a Streamrader object.
                inputfile = File.OpenText("employee.txt");
    
                //Clear anything currently in the ListBox.
                employeesListBox.Items.Clear();
    
                //Read the file's contents.
    
                while (!inputfile.EndOfStream)
                {
                   //Get employee data
                   //employeeData = inputfile.ReadLine();
                   employeeData = inputfile.ReadLine().Replace("\"", "");
    
                   var IdandName = String.Join(",", employeeData.Split(',').Take(2));
    
                   
                   //Add the employeeData 
                   employeesListBox.Items.Add(IdandName);
                   // var te = employeeData.Replace(IdandName + ",", "");
                   dict.Add(IdandName, employeeData);
                }
                //Close the file.
                inputfile.Close();
             }
          catch (Exception ex)
          {
                //Display an error message.            MessageBox.Show(ex.Message);
          }
    
          }
    
          private void employeesListBox_SelectedIndexChanged(object sender, EventArgs e)
          {
             // Get the currently selected item in the ListBox.
             string curItem = employeesListBox.SelectedItem.ToString();
    
             //Create an instance of EmployeeDetailsForm
             EmployeeDetailsForm empdetForm = new EmployeeDetailsForm();
             string value = dict[curItem].Replace(curItem + ",", "");
             employeeDetailsLabel.Text = value;
    
             empdetForm.ShowDialog();
           
          }
    

     

    Monday, December 11, 2017 4:07 PM
  • There is always TextFieldParser which has a property (HasFieldsEnclosedInQuote) to indicate data is enclosed in quotes and with that give you the data within the quotes only.

    See the following answer and make sure to read the first comment to the answer.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, December 11, 2017 4:22 PM
    Moderator
  • Following my previous suggestions:

    private void employeesListBox_SelectedIndexChanged(object sender, EventArgs e) { // Get the currently selected Employee in the ListBox. Employee curEmployee = (Employee)employeesListBox.Items[bs.Position]; // Add another constructor to the EmployeeDetailsForm to pass an Employee parameter // In that constructor, databind all your TextBoxes (and labels if you'd like) EmployeeDetailsForm empdetForm = new EmployeeDetailsForm(curEmployee); empdetForm.ShowDialog(); } public class EmployeeDetailsForm { private Employee CurrentEmployee; private BindingSource bs; // add this constructor public EmployeeDetailsForm(Employee employee) : this() { this.CurrentEmployee = employee; this.bs = new BindingSource();

    // UPDATED 12-11-2017 Forgot to include the following

    this.bs.DataSource = this.CurrentEmployee

    this.DataBind(); } private void DataBind() { // I don't know if you still want this: // this.employeeDetailsLabel.DataBindings.Add("Text", bs, "Name"); this.txtName.DataBindings.Add("Text", bs, "Name"); this.txtDept.DataBindings.Add("Text", bs, "Department"); this.txtPosition.DataBindings.Add("Text", bs, "Position"); // etc. for the rest of them } }


    Couldn't be much easier than that!

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com


    • Edited by BonnieBMVP, Moderator Tuesday, December 12, 2017 2:11 AM Updated to include something I inadvertantly left out of original reply
    Monday, December 11, 2017 6:09 PM
    Moderator
  • Hello gamaz123,

    you should set the label as public so that you could access the label text from current form.

    And your code should be like below.

                EmployeeDetailsForm empdetForm = new EmployeeDetailsForm();
    
                empdetForm.employeeDetailsLabel.Text = value;
    
                empdetForm.ShowDialog();

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by gamaz123 Tuesday, December 12, 2017 5:42 PM
    Tuesday, December 12, 2017 1:46 AM
    Moderator

  • BTW, I inadvertently left out an important line of code in my previous reply. I have edited that previous reply to include that line (in bold). Sorry if anyone tried it without that, because it wouldn't have worked!!!  =0( 

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Tuesday, December 12, 2017 2:16 AM
    Moderator
  • Thanks that took care of the issue.
    Tuesday, December 12, 2017 5:40 PM
  • Since I have already followed a particular path I resolved my issue with Neil's advise. Anyway I would like to thank you for your generous help as you  have done so with my previous post. Thanks.
    Tuesday, December 12, 2017 5:42 PM
  • Since I have already followed a particular path I resolved my issue with Neil's advise. Anyway I would like to thank you for your generous help as you  have done so with my previous post. Thanks.

    You're welcome ... and please consider my suggestions for any future development you might do, because in the long run, it's actually a better and easier methodology.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Wednesday, December 13, 2017 5:43 PM
    Moderator