10 Replies - 753 Views - Last Post: 10 May 2015 - 07:16 PM Rate Topic: -----

#1 bob0020   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 15-November 14

Edit Button

Posted 10 May 2015 - 02:23 AM

Can someone help me improve my program so that it can edit a selected question? I'm also having a problem with my add button. The new question I add saves ok to my txt file but in doing so it wipes out the questions I already saved. The code I have commented out is where I am having the problem. Thanks

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace MoveGame
{
    public partial class Questions : Form
    {
        private Menu menu;

        string[] questions = new string[20];		//keep things simple with some global arrays
        string[] Ans1 = new string[20];
        string[] Ans2 = new string[20];
        string[] Ans3 = new string[20];
        string[] Ans4 = new string[20];
        string[] correctAns = new string[20];
        byte Question_Num = 0;


        public Questions()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            questions[Question_Num] = tbQuestion.Text;
            Ans1[Question_Num] = tbAns1.Text;
            Ans2[Question_Num] = tbAns2.Text;
            Ans3[Question_Num] = tbAns3.Text;
            Ans4[Question_Num] = tbAns4.Text;
            correctAns[Question_Num] = cbCorrectAns.Text;
            Question_Num++;


            // create a writer and open the file
            TextWriter tw = new StreamWriter("StoredQuestions.txt");
            for (int num_Question = 0; num_Question < Question_Num; num_Question++)
            {

                // write a line of text to the file
                //as commas are used to separate the data fields they cannot be allowed to
                //occur in the data so replace them with alternative character
                Ans1[num_Question] = Ans1[num_Question].Replace(",", "~");
                Ans2[num_Question] = Ans2[num_Question].Replace(",", "~");
                Ans3[num_Question] = Ans3[num_Question].Replace(",", "~");
                Ans4[num_Question] = Ans4[num_Question].Replace(",", "~");
                tw.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", questions[num_Question], Ans1[num_Question],
                    Ans2[num_Question], Ans3[num_Question], Ans4[num_Question], correctAns[num_Question]);
            }
            // close the stream
            tw.Close();
        }
        public Questions(Menu menu)
        {
            // TODO: Complete member initialization
            this.menu = menu;
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            string[] Data; //string array
            string Input = null;      //temp string buffer for line of text
            byte Read_Question_Num = 0;		//count number of records read
            lblQuestions.Text = "";		//clear display 
            TextReader tr = new StreamReader("StoredQuestions.txt");
            try		//When loading data from file errors such as file not found may occur
            {
                // create reader & open file

                // read a line of text
                while ((Input = tr.ReadLine()) != null)//keeping reading while another line exists
                {
                    Data = Input.Split(','); //split from single string into array of strings
                    questions[Read_Question_Num] = Data[0];
                    Ans1[Read_Question_Num] = Data[1].Replace("~", ",");   //undo the character swap

                    //Output Data to Label
                    lblQuestions.Text += questions[Read_Question_Num].PadLeft(16)
                        + Ans1[Read_Question_Num].PadLeft(30)
                        + Ans2[Read_Question_Num].PadLeft(30)
                        + Ans3[Read_Question_Num].PadLeft(30)
                        + Ans4[Read_Question_Num].PadLeft(30)
                        + correctAns[Read_Question_Num] + "\n";
                    Read_Question_Num++;  //complete processing of a record
                }//while read

                tr.Close();	// close the stream
            }//try
            catch
            {	//message to inform user about error
                lblQuestions.Text = "Error in data file";
                tr.Close();	// close the stream
            }//catch	
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            /*questions.Show();
            this.Dispose();*/

        }

        private void BtAdd_Click(object sender, EventArgs e)
        {
            /*AddNew();
            questions.Load_Questions();
            this.Dispose();
            questions.Show();*/

        }

        private void Edit()
        {
            string question = tbQuestion.Text;
            string Ans1 = tbAns1.Text;
            string Ans2 = tbAns2.Text;
            string Ans3 = tbAns3.Text;
            string Ans4 = tbAns4.Text;
            int CorrectAns = cbCorrectAns.SelectedIndex + 1;
        }
        /*
                        if (listView1.Items.Count > Num_Quest)
                {
                    listView1.Items.RemoveAt(Num_Quest);
                }

                listView1.Items.Insert(Num_Quest, questions[Num_Quest].PadLeft(16)
                            + Ans1[Num_Quest].PadLeft(30)
                            + Ans2[Num_Quest].PadLeft(30)
                            + Ans3[Num_Quest].PadLeft(30)
                            + Ans4[Num_Quest].PadLeft(30)
                            + correctAns[Num_Quest].PadLeft(30));
            }

            private void saveQuestions()
            {
                // create a writer and open the file
                TextWriter tw = new StreamWriter("storeQuestions.txt");
                for (int questionNum = 0; questionNum < numQuestions; questionNum++)
                {

                    // write a line of text to the file
                    //as commas are used to separate the data fields they cannot be allowed to
                    //occur in the data so replace them with alternative character
                    Ans1[questionNum] = Ans1[questionNum].Replace(",", "~");
                    Ans2[questionNum] = Ans2[questionNum].Replace(",", "~");
                    Ans3[questionNum] = Ans3[questionNum].Replace(",", "~");
                    Ans4[questionNum] = Ans4[questionNum].Replace(",", "~");
                    tw.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", questions[questionNum], Ans1[questionNum], Ans2[questionNum]
                        , Ans3[questionNum], Ans4[questionNum], correctAns[questionNum]);
                }
                // close the stream
                tw.Close();
            }

            private void btnAdd_Click(object sender, EventArgs e)
            {
                addQuestion();
            }//btnSave

            private void btnEdit_Click(object sender, EventArgs e)
            {
                int editNum_Quest = listView1.SelectedIndices[0];
                editQuestion(editNum_Quest);

            }

            private void QuizQuestions_Load(object sender, EventArgs e)
            {

            }
        }
    }

       
            private void btnEdit_Click(object sender, EventArgs e)
            {
        
            }

        
            }


    }
}
    





Is This A Good Question/Topic? 0
  • +

Replies To: Edit Button

#2 Damage   User is offline

  • Lord of Schwing
  • member icon

Reputation: 300
  • View blog
  • Posts: 1,989
  • Joined: 05-June 08

Re: Edit Button

Posted 10 May 2015 - 03:43 AM

i think you need to set your streamwriter to append. Overload it like this

TextWriter tw = new StreamWriter("storeQuestions.txt",true);



that should add the new stuff to the end of the existing file instead of overwriting it
Was This Post Helpful? 1
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6536
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Edit Button

Posted 10 May 2015 - 03:51 AM

About 3/4 the way down this article on common homework problems is 'The Quiz Program'.
http://www.dreaminco...cle-you-wanted/

Before working on advanced features I would suggest you work on basic good practices.

Looking at your code you have some bad practices in play that need your immediate attention.
These will form bad habits quickly and should be worked on. This is part of what I mean by "learn foundation concepts first".

Problem 1: Use of GUI controls as your variables.
You have numerous places where you are doing things like: SomeMethodCall(TextBox43.Text);
Your textboxes and other GUI elements are not meant to be your variables to hold values. They exist only to be a way for the user to interact with the data held in the logic code *behind* the GUI. You should have properties bound to the GUI. When the user changes something in a textbox it updates the property in your code. When the property gets a new value, the GUI is updated. But your logic always uses the property not the GUI element.
There is a tutorial on properties linked in my signature block.

Problem 2: This bit about button1 and textbox14 is just horrible. If you are working in old 1980's WinForms for Win98 and WinXP programs then name your control as soon as you make it before doing anything else with it. txtbxFirstName is so much easier to maintain than textbox32. Same with "frmConnectionSettings" instead of "form2" or "wndCustomerDetails" than "window4". If you are making programs for current OSes like Win7/8 then you should be working in WPF where the controls don't need to be named 90% of the time, but the same practice of giving meaningful names should still be followed in the few cases where they are needed.

Problem 3: Don't put meaningful operational code in GUI control handlers. You have a lot of places where the work is being done in the button event handler instead if in a dedicated method. Instead you want that handler to just direct action to the first methods, not actually perform the actions.
btnSave_Click(object sender, eventargs e)
{
   SaveSettings(); // Call the save method
   SavePlayers();
   SaveWindowGeometry();
   // Do NOT put all the save code here
}

This way you can call the same save methods independently from code without having to either duplicate code (evil practice) or without calling the button handler. If you are using WinForms then you have a .Click event handler. If you are writting in WPF then don't call the .Click event but instead create Commands and activate those. The .Click handler in WPF is kind of a carry-over to give WinForms coders a comfortable migration path but is not considered the way a modern profession WPF coder works.

Problem 4:
Eye sore code.
Take the extra 2 minutes to clean up your code to make it easy to read, easy to follow, and most important, easy to manage.
  • Kill all those dead blank lines at the ends of methods.
  • Wrap groups of methods that go together in #region blocks so you can find all your sending code and receiving code easily for example.
  • Get your lines aligned. Control-K, Control-D will do that for you (Think of it as Klean Document)


Problem 5: Decent naming
Methods like private void ClientSession(object sender, eventargs e); don't follow established naming style guides.
A method performs an action. By convention for decades methods are named as verbs to show what they do. Nouns like ClientSession would be presumed to be a property by any other coder looking at your code. private void CreateClientSession(object sender, eventargs e); on the other hand shows that it does something (a method) not that it is something (a variable).

Problem 6: Use of WinForms after the year 2001.
If this is school homework and you are instructed to use WinForms then keep going. If you are teaching yourself then stop using this 1995 WinForms crap and move to modern WPF. WinForms is legacy/end-of-life. Look at Monster.com and CareerBuilder.com and you'll see that employers want WPF skilled developers. Learning this old-school stuff does nothing for your career or potential to get hired.

Problem 7: Trying to run before you can crawl.
You're not at a point in your self-education where you should be trying to archetect/design an entire program from scratch. Its a common misstep that rookies make. Somehow they think "I don't know how to code so I'll make a program from scratch to learn." That never turns out well. You have to undertand the coding language you've chosen, its strength and weaknesses and most importantly its foundation design concepts before you can even think about trying to design a program.

Looking at your code its very clear that C# is new to you... GUI programming is new for you... That you don't understand the idea of using properties instead of using your WinForm controls like they are variables. That you don't even realize that by using WinForms you've chosen a dieing GUI technology that hasn't been in employer demand for years. That you haven't worked through some of the most basic debugging tutorials which would give you some skills to solve really basic problems.

I strongly urge you to set this project aside, pick up one or two "Learn C# in 30 days" books and just work them from cover to cover. They are guided tutorials not reference books like a dictionary; only to be opened when you get in trouble. So many bad things I see here would be taken care of if you would just work on learning at this stage and leave the designing until you are more ready. I think if you then look at this same project with all the new knowledge you'll pick up you'll see where I'm coming from.

I'm not going to go into a long critique of your code. And I don't want you to feel like I'm just out to pick on you. I'm just pointing out a couple of many foundation concepts you didn't pickup up in the early stages of learning C#. You can't leap-frog the learning process by trying to build a program in your first month. Nobody can. Its not just you. Nobody in the first month of a new discipline has enough knowledge to jump in and start designing finished solutions: Not carpentry, not automotive design, not software engineering. C# is a foreign language with its own syntax. You aren't going to say "I know no Russian. I'm going to write a Russian mystery novel as my vehicle to learn the language." Same here with programming.

Posted Image
Was This Post Helpful? 0
  • +
  • -

#4 bob0020   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 15-November 14

Re: Edit Button

Posted 10 May 2015 - 07:14 AM

View PostDamage, on 10 May 2015 - 03:43 AM, said:

i think you need to set your streamwriter to append. Overload it like this

TextWriter tw = new StreamWriter("storeQuestions.txt",true);



that should add the new stuff to the end of the existing file instead of overwriting it

Firstly Thanks!
I made the change you suggested but I'm now getting an error with my ReadLine

"Error 2 'System.IO.TextWriter' does not contain a definition for 'ReadLine' and no extension method 'ReadLine' accepting a first argument of type 'System.IO.TextWriter' could be found (are you missing a using directive or an assembly reference?)"

 TextWriter tw = new StreamWriter("storeQuestions.txt", true);

            try		//When loading data from file errors such as file not found may occur
            {
                // create reader & open file

                // read a line of text
                while ((Input = tw.ReadLine()) != null)//keeping reading while another line exists
                {
                    Data = Input.Split(','); //split from single string into array of strings
                    questions[Read_Question_Num] = Data[0];
                    Ans1[Read_Question_Num] = Data[1].Replace("~", ",");   //undo the character swap


Was This Post Helpful? 0
  • +
  • -

#5 bob0020   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 15-November 14

Re: Edit Button

Posted 10 May 2015 - 07:20 AM

Thank you for your reply, the code I'm using is the way I have been taught to use it. I'm aware there are better solutions and techniques which I could neh should apply but my tutor is adamant that I follow his techniques. I will take all your advice on board but as it stands can you offer me some advice on how I could get the edit question portion of my program working? This is not the full program I could attach the working quiz game if that would help?

This post has been edited by tlhIn`toq: 10 May 2015 - 07:49 AM
Reason for edit:: No need to quote the entire previous message: We all see it.

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6536
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Edit Button

Posted 10 May 2015 - 07:53 AM

I already pointed you at an article on doing a quiz program.
Honestly I'm not going down the road of "I know its a horrible design, but here are a few band-aides to put on top of the patches to put on top of the fixes". That just becomes a deep dark hole of "okay, now what" and 10 other readers thinking that the advice was a recommendation of how to do it.
Was This Post Helpful? 0
  • +
  • -

#7 bob0020   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 15-November 14

Re: Edit Button

Posted 10 May 2015 - 08:03 AM

View PosttlhIn`toq, on 10 May 2015 - 07:53 AM, said:

I already pointed you at an article on doing a quiz program.
Honestly I'm not going down the road of "I know its a horrible design, but here are a few band-aides to put on top of the patches to put on top of the fixes". That just becomes a deep dark hole of "okay, now what" and 10 other readers thinking that the advice was a recommendation of how to do it.


Not to sound ungrateful but that article is not particularly helpful to me for the stage that I'm at. I've designed my quiz it runs fine, it understands the users choice and responds to their choice with a message stating the answer was either correct or incorrect. The program keeps score and times the length of each question as well as the total time taken to complete the quiz. I've achieved almost everything I've set out to except for the editing of the questions which I have stored in my txt file.
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6536
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Edit Button

Posted 10 May 2015 - 12:52 PM

That's fine. My feelings aren't hurt or anything. If you're not a place where you can start doing OOP design, and not interested in moving your skillset forward to OOP design it doesn't affect me. Best of luck with your project.
Was This Post Helpful? 0
  • +
  • -

#9 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6833
  • View blog
  • Posts: 28,342
  • Joined: 12-December 12

Re: Edit Button

Posted 10 May 2015 - 04:03 PM

Quote

"Error 2 'System.IO.TextWriter' does not contain a definition for 'ReadLine' ..

TextWriter doesn't have any Read methods, only Write methods. MSDN

I'm not sure why you are trying to read the file - a comment in your code suggests that you intended to create a Reader - but it is not a good idea to attempt to read, and write to, a file at the same time.

You said you have a problem with your Add button, but you have three Add buttons. In any case, you'll need to provide more information and describe what you have attempted.
Was This Post Helpful? 0
  • +
  • -

#10 bob0020   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 15-November 14

Re: Edit Button

Posted 10 May 2015 - 05:10 PM

Sorry, I'm only meant to have the one add button I've fixed that now. I've created a quiz and the add button is supposed to add the new question too my existing set of questions found in my StoredQuestions.txt file. At present the new question does add but in doing so it erases the existing questions in the file. Is there a way I can add the question without loosing my existing questions?

This post has been edited by andrewsw: 10 May 2015 - 11:13 PM
Reason for edit:: Removed previous quote, just press REPLY

Was This Post Helpful? 0
  • +
  • -

#11 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 7234
  • View blog
  • Posts: 24,517
  • Joined: 05-May 12

Re: Edit Button

Posted 10 May 2015 - 07:16 PM

Using the append flag should have preserved your files previous contents. You must be doing something else to wipe it. Post your current code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1