Hello!

I am having a bit of a hard time figure out how to code this thing..
I have just started coding by using windows form application and need some help..

I have successfully coded so that I can open a txt file without any problem, but it is reading it and giving the text in the file some values to use for this windows app..

What I have done so far is to make a window with a Combobox and adding 4x textbox.

I have added the following into the comboBox:
Item
Name
Thing

The text.txt file contains:
Item 20 Mouse 34 32
Name 09 Bob 21 43
Thing 12 Boat 123 43

-----------------------------------------

What I want to do is following:
Opening a txt file [done]
Reading a txt file [not coded]
Giving values to each string [not coded]
If I choose (for example) Name in the comboBox, then "09 Bob 21 43" should appear in each textbox.

I hope you could help me, or atleast give me something to work on..

I can read a txt file and write out what I want in the console application by using while.. but that is not the case in windows form application..

Sorry for the long post but I am not so great with explaining myself than showing my problem with pictures etc..

Please ask anything if there is something I have missed or should show.

Sincerely~

First thing needed is how are coding the app? Are you using VC++ with CLR? or some other library? Also you should show what code you've got. Include what effort you've made to research this question.

Edited 3 Years Ago by tinstaafl

I am using VC++ with CLR

I will show you what I have coded so far:

My window:

Image file mediafire

When I select something it should write as such:

Image file mediafire

My current code:

#include <string>
#include <fstream>
#include <istream>
#include <streambuf>
#include <iostream>
#include <sstream>


private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             std::ifstream myfile;
             myfile.open("text.txt", std::ifstream::in); //Reading txt file
             if(myfile.is_open())
             {
                 MessageBox::Show("File is open"); //checking if txt file loaded
             }else
             {
                 MessageBox::Show("File is not open"); //loading failed
             } 

             //strings to use as values for items in txt
             String^ itemname;
             int value1;
             int value2;
             int value3;
             int value4;

             while(myfile >> itemname >> value1 >> value2 >> value3 >> value4)
             // which I used to work in windows console application VC++ Win32
         }
private: System::Void comboBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {

                //test label
                 label1->Text = comboBox1->Text; //itemname

                 //Testing out giving values to textboxes manually
                 if(comboBox1->Text == "Name")
                 {
                     textBox1->Text = "09"; //value1
                     textBox2->Text = "Bob"; //value2
                     textBox3->Text = "21"; //value3
                     textBox4->Text = "43"; //value4
                 }
                 if(comboBox1->Text == "It3m")
                 {
                     textBox1->Text = "54";
                     textBox2->Text = "12";
                     textBox3->Text = "1341";
                     textBox4->Text = "12";
                 }
                 if(comboBox1->Text == "Thing")
                 {
                     textBox1->Text = "12";
                     textBox2->Text = "Boat";
                     textBox3->Text = "123";
                     textBox4->Text = "43";
                 }


             }

The error I get:

Error   2   error C1903: unable to recover from previous error(s); stopping compilation c:\c++\readingtxtfile2\readingtxtfile2\Form1.h  238
Error   1   error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::ifstream' (or there is no acceptable conversion) c:\c++\readingtxtfile2\readingtxtfile2\Form1.h  238

Edited 3 Years Ago by Xakzi

You should use std::getline to line by line from text file.
For your issue, I create simple code to resolve your issue

#pragma once

#include <string>
#include <fstream>
#include <istream>
#include <streambuf>
#include <iostream>
#include <sstream>


namespace TestForm {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Form1
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        ref class ItemData
        {
        public: System::String^ Item;
        public: System::String^ Data;
        public:
            ItemData(String^ sItem, String^ sData)
            {
                Item = gcnew String(sItem);
                Data = gcnew String(sData);
            }
        public:
            virtual System::String^ ToString() override
            {
                return Item;
            }
        };
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::ComboBox^  comboBox1;
    protected: 
    private: System::Windows::Forms::TextBox^  textBox1;

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->comboBox1 = (gcnew System::Windows::Forms::ComboBox());
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->SuspendLayout();
            // 
            // comboBox1
            // 
            this->comboBox1->FormattingEnabled = true;
            this->comboBox1->Location = System::Drawing::Point(60, 55);
            this->comboBox1->Name = L"comboBox1";
            this->comboBox1->Size = System::Drawing::Size(146, 21);
            this->comboBox1->TabIndex = 0;
            this->comboBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::comboBox1_SelectedIndexChanged);
            // 
            // textBox1
            // 
            this->textBox1->Location = System::Drawing::Point(59, 107);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(146, 20);
            this->textBox1->TabIndex = 1;
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(384, 266);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->comboBox1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
                 std::ifstream myfile;
                 std::string strline;
                 myfile.open("C:\\Text.txt", std::ifstream::in); //Reading txt file
                 if(myfile.is_open())
                 {
                     MessageBox::Show("File is open"); //checking if txt file loaded
                 }else
                 {
                     MessageBox::Show("File is not open"); //loading failed
                 } 

                 //strings to use as values for items in txt
                 String^ itemname;
                 String^ sItem, ^sData;

                 // read lines from text file
                 for(std::string sline; std::getline(myfile, sline); )
                 {
                     itemname = gcnew String(sline.c_str());
                     int nIndex = itemname->IndexOf(' ');

                     if(nIndex > 0)
                     {
                         sItem = itemname->Substring(0, nIndex);
                         sData = itemname->Substring(nIndex + 1);

                         comboBox1->Items->Add(gcnew ItemData(itemname->Substring(0, nIndex),
                             itemname->Substring(nIndex + 1)));
                     }
                     else
                     {
                         sItem = itemname;
                         sData = "";
                         comboBox1->Items->Add(gcnew ItemData(itemname, ""));
                     }
                 }
             }
    private: System::Void comboBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {
                 ItemData^ data = (ItemData^)comboBox1->SelectedItem;
                 textBox1->Text = data->Data;
             }
};
}

I used a StreamReader to show every line of a file called "test.txt":

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) 
        {                
            String^ fileName = "test.txt";
            try 
            {
                StreamReader^ DataIn = File::OpenText(fileName);
                String^ DataStr;
                int count = 0;
                while ((DataStr = DataIn->ReadLine()) != nullptr) 
                {
                    count++;
                    MessageBox::Show("Line " + count + " " + DataStr);                      
                }
            }
            catch (Exception^ e)
            {
                if (dynamic_cast<FileNotFoundException^>(e))
                    MessageBox::Show("File " + fileName + " not found");
            }
        }

Also don't forget to add the line using namespace System::IO
The only thing that remains to do is using the Split method of the DataStr to create an array of strings and stuff your textboxes with them.
Like so:

array<String^>^ result;
array<Char>^ separ = gcnew array<Char>{' '};
result = DataStr->Split(separ, StringSplitOptions::None);

Edited 3 Years Ago by ddanbe: addition

@ddanbe

Sorry mate, but that code is too hard for me to really understand.. seems hard to edit it..
by the way, that code reads whole line only right?

@thanhvy
This code works great thanks, but how would I do to use 4 different textboxes?

I have tried to use 2 different textboxes but can't seem to make it work, I get this error.

Error   1   error C2661: 'readingtxtfile3::Form1::ItemData::ItemData' : no overloaded function takes 2 arguments    c:\c++\readingtxtfile3\readingtxtfile3\Form1.h  160

Edited 3 Years Ago by Xakzi

Couldnt get the edit post button on my previous comment, sorry for double comments.

I have looked up arguments ..

What should I do since I can not use more then 2 arguments with an override?

Edited 3 Years Ago by Xakzi

Hello Xakzi.
Because you are using Visual C++, I thought I give an example in a more .NET style way.
I just gave an example on how you could do it, but you probably have to work it out more in your Combobox SelectedIndexChanged event handler.
I'll repost my code here with some comments, in the hope you understand a bit more of it. The example read your test file line by line and splits every line in in individual strings. See also debug window.
With the array of result strings you could easily fill in the Text of your Textboxes.

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) 
        {                
            String^ fileName = "C:\\test.txt"; //path to the file to open.
            //try block always gets executed, if and error occurs it is handled in the catch block
            try 
            {
                // a StreamReader is like ifstream
                StreamReader^ DataIn = File::OpenText(fileName); // we go to the catch block if error
                // definitions
                String^ DataStr;
                int count = 0;
                //array will contain the results of the DataStr split
                array<String^>^ result;
                //the string Split method needs an array of chars to split on
                //in this case, we have an array of only 1 char: the blank.
                array<Char>^ separ = gcnew array<Char>{' '};

                //we read a line of our file and put it in DataStr as long as it is not equal to null
                while ((DataStr = DataIn->ReadLine()) != nullptr) 
                {
                    count++; //Linecount in the file
                    // MessageBox, just for testing if we read the line successfully
                    // or set a breakpoint and watch it in the debugger
                    MessageBox::Show("Line " + count + " " + DataStr);
                    //split the line
                    result = DataStr->Split(separ);
                    // if line 1 of the testfile is read, result[0] will contain "Item"
                    // result[1] will be "20" etc. see also the debug picture
                }
            }
            catch (Exception^ e)
            {
                if (dynamic_cast<FileNotFoundException^>(e))
                    MessageBox::Show("File " + fileName + " not found");
            }
        }

Edited 3 Years Ago by ddanbe: addition

Attachments debug.png 47.86 KB

@ddanbe

Thanks a lot!
Got it working with the combobox & textboxes too.

I put the code within the Combobox SelectedIndexChanged event handler
and added this :

if(comboBox1->Text == result[0])
                         {
                             textBox1->Text = result[1];
                             textBox2->Text = result[2];
                             textBox3->Text = result[3];
                             textBox4->Text = result[4];
                         }

within the "split the text" coding.

Thanks a lot for your help.

@ddanbe
hello mate.. sorry but I need some help yet again..

lets say I want to add a line in the txt, example
"This is a line"

And I would all that to be one whole string..
so if I have

Item 10 20 30 40 "This is a line"

I would like that "This is a line = result[5].

how could I manage that?

mm, no not like that..

I would like "This is a line" to be in the txt file as one string..
making the program read from first quote to the next qoute...

I would want "This is a line" to be in the text file and I use result[x] to write it out.

Oh, that's simple!
If you have extra string in your lines in the textfile, the string Split method will take care of the rest. It should return the extra string in the results array. If you would have 10 or even more strings on a line in your file, no problem either.

Edited 3 Years Ago by ddanbe: slight addition

I see your point, and I just thought of a way to take an advantage of that..
instead of split the strings with a Space, I could split it with a quote instead..
Thanks for the help once again !

This article has been dead for over six months. Start a new discussion instead.