This is a pretty simple program. It IS a homework project. The program should start, read a .txt file, populate the name list and when you click on the name, the phone number is displayed. I have it coded, no errors, no warnings. It will not read the .txt file and I can't figure out why. I've been scouring my book, youtube, even here, but can't pin it down. Any help would be appreciated. Here is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Phonebook
{
struct PhoneBookEntry
{
public string name;
public string phone;
}
public partial class Form1 : Form
{
// FIeld to hold a list of PhoneBookEntry objects.
private List<PhoneBookEntry> phoneList = new List<PhoneBookEntry>();
public Form1()
{
InitializeComponent();
}
// The ReadFile method reads the contents of the
//PhoneList.txt file and tores it as PhoneBokeEntry
// objects in the phoneList.
private void ReadFile()
{
try
{
StreamReader inputFile; // To read the file
string line; // To hold a line from the file
// Create an instance of the PhoneBookEntry structure.
PhoneBookEntry entry = new PhoneBookEntry();
// Create a delimiter array.
char[] delim = { ',' };
// Open the PhoneList file.
inputFile = File.OpenText("PhoneList.txt");
// Read the lines from the file.
while (!inputFile.EndOfStream)
{
// Read a line from the file.
line = inputFile.ReadLine();
// Tokenize the line
string[] tokens = line.Split(delim);
// Store the tokens in the entry object.
entry.name = tokens[0];
entry.phone = tokens[1];
// Add the entry object to the List.
phoneList.Add(entry);
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
// The DisplayNames method displays the list of names
// in the namesListBox conrol.
private void DisplayNames()
{
foreach (PhoneBookEntry entry in phoneList)
{
nameListBox.Items.Add(entry.name);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Read the PhoneList.txt file.
ReadFile();
// DIsplay the names.
DisplayNames();
}
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the index of the selected item.
int index = nameListBox.SelectedIndex;
// Display the corresponding phone number.
phoneLabel.Text = phoneList[index].phone;
}
private void exitButton_Click(object sender, EventArgs e)
{
// close the form.
this.Close();
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
}
Related
Cannot enter text from class to textbox in form.
We set a keypress event in the MyTreeView class.
The text box cannot contain characters.
What should I do?
*set of textBox1.
*Change Modifiers for textBox1 properties from private to public
*Change keypress event from private to public
*(It didn't work well, so I keep it private now.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace treeview
{
public partial class Form1 : System.Windows.Forms.Form
{
MyTreeView m_tree_view = new MyTreeView();
public Form1()
{
try
{
InitializeComponent();
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];
m_tree_view.Location = new System.Drawing.Point(0, 0);
m_tree_view.Size = ClientSize;
m_tree_view.AllowDrop = true;
tree1[0] = new System.Windows.Forms.TreeNode("TreeNode1");
tree1[1] = new System.Windows.Forms.TreeNode("TreeNode2");
m_tree_view.Nodes.Add("Node1");
Controls.Add(m_tree_view);
}
catch
{
}
}
//This is the code I added.
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class MyTreeView : System.Windows.Forms.TreeView
{
public MyTreeView()
{
try
{
//This is the code I added.
KeyPress += MyTreeView_KeyPress;
}
catch
{
}
}
//This is the code I added.
private void MyTreeView_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
Console.WriteLine("key_press_ok");
//error code↓
//textBox1.Text = "sample";
}
}
}
If you want just to click an button and then print some text i don't understand why you are making another class.
Will be good to make your code efficient and not complicated.
In the main class
private void SendText_Click(object sender, EventArgs e)
{
textBox1.Text = "hi";
}
But if you want to make it complicated and make a class you shuld return i variable and send it to the other class the you can use it.
Learn how to use Public and private first and then use them.
You shuld have a public class which send data and the private to recive and process.
add (Exception ex) to your try catch.
so do:
try
{
// your code
}
catch (Exception ex)
{
MessageBox.Show(ex, "Error in (add where the error is)");
Console.WriteLine(ex);
}
So you will get a detailed Exception Message, maybe it helps you or maybe you will post it here, so we can see what the problem is.
And because you have System.Windows.Forms in your Using Directive
using System.Windows.Forms;
so
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];
is redundant and can be shortened to:
TreeNode[] tree1 = new TreeNode[2];
I'm a newbie in C# and not native English (sorry for that); I am using Visual Studio 2017 using WinForm application.
To test some features to be added in an already existing project, I have created a new Winform application. This simple software writes and reads strings to and from a file. So, in the form I have 2 textboxes and 3 buttons: Save to file, Read from file and Update. To reduce the confusion in the bigger project, I've decided to split the methods in different classes: each one does one job and the form script has the minimum quantity of code possible.
The 3 .cs files (clases) are:
The form partial class,
SaveFile class, where the job to save the string to a text file is carried out,
OpenFile class, where the job to read the text file returning the lines in a list of strings.
All the 3 classes have been created and added to the project ProvaSalvataggioFile2.
So, the form class is (take note only of the methods' name, I have written all the code for completeness, if someone wants to test the code)
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string inputString = tbInputText.Text;
if (inputString.IsValidString())
{
inputString.SaveToFile();
}
else
{
MessageBox.Show("The input string is not valid: please insert a valid string",
"Empty or null input string",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tbInputText.Focus();
}
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
List<string> textFileContent = new List<string>();
textFileContent = OpenTextFile();
tbFileText.Text = string.Join(Environment.NewLine, textFileContent);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (File.Exists(fileName))
{
List<string> textReadFromFile = new List<string>();
textReadFromFile = File.ReadAllLines(fileName).ToList();
tbFileText.Text = string.Join(Environment.NewLine, textReadFromFile);
}
}
}
}
The SaveFile class is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public static class SaveFile
{
public static bool IsValidString(this string stringToValidate)
{
bool result = true;
if (string.IsNullOrEmpty(stringToValidate))
{
result = false;
}
return result;
}
public static bool SaveToFile(this string stringToSave)
{
bool result = true;
//bool savedfile;
DialogResult messageBoxResult;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = false;
saveFileDialog1.OverwritePrompt = false;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (File.Exists(saveFileDialog1.FileName))
{
messageBoxResult = MessageBox.Show("The file is already existing: do you want:\n\t\u22c5OVERWRITE the file [YES]\n\t\u22c5APPEND data in the file [NO]\n\t\u22c5Use another file [CANCEL]",
"Overwrite file",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Asterisk,
MessageBoxDefaultButton.Button3);
if (messageBoxResult == DialogResult.Yes)
{
messageBoxResult = MessageBox.Show(("Are you sure to overwrite the file in\n" + saveFileDialog1.FileName),
"Sure to overwrite file?",
MessageBoxButtons.OKCancel);
if (messageBoxResult == DialogResult.OK)
{
try
{
File.WriteAllText(saveFileDialog1.FileName, stringToSave);
result = true;
}
catch
{
result = false;
}
}
}
else if (messageBoxResult == DialogResult.No)
{
//MessageBox.Show(("Message to save: \"" + stringToSave + "\"\nin \"" + saveFileDialog1.FileName));
try
{
File.AppendAllText(saveFileDialog1.FileName, (Environment.NewLine + stringToSave));
result = true;
}
catch
{
result = false;
}
}
else
{
messageBoxResult = MessageBox.Show("Please enter a new filename",
"Save in a new file",
MessageBoxButtons.OKCancel);
if (messageBoxResult == DialogResult.OK)
{
stringToSave.SaveToFile();
}
}
}
else
{
File.WriteAllText(saveFileDialog1.FileName, stringToSave);
result = true;
}
}
return result;
}
}
}
And the OpenFile class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public class OpenFile
{
public string fileName { get; set; }
public List<string> OpenTextFile()
{
List<string> textReadFromFile = new List<string>();
//textReadFromFile = new List<string>();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.CheckPathExists = true;
openFileDialog1.CheckFileExists = true;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = openFileDialog1.FileName.ToString();
textReadFromFile = File.ReadAllLines(openFileDialog1.FileName).ToList();
}
return textReadFromFile;
}
}
}
Now, if I put all the methods in the form class, all works just fine, with no problems (the application is stupid, only made to test the logic behind). But if I split the code in the 3 classes, I have:
Error CS0103 The name 'OpenTextFile' does not exists in the current context ProvaSalvataggioFile2 Form1.cs 41
Error CS0103 The name 'fileName' does not exists in the current context ProvaSalvataggioFile2 Form1.cs 47
Error CS0103 The name 'fileName' does not exists in the current context ProvaSalvataggioFile2 Form1.cs 50
So there must be some problem related with the splitting in classes. I have tried googling the error, but it seems that this error comes out in very different occasions and for different reasons (nothing in common with mine). I argue that I have missed something in the process of adding the new class or in the code defining the class.
I repeat myself, if I copy and paste the methods in the form class, the application works perfectly, but the same methods put in a separate class (but in the same file of the form class) doesn't.
The problem here is that you are trying to access members of the OpenFile class within the MainForm class. Initialize an instance of OpenFile and keep it in a variable within your MainClass to reuse
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public partial class MainForm : Form
{
// Initialize OpenFile
private readonly OpenFile openFile = new OpenFile();
public MainForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string inputString = tbInputText.Text;
if (inputString.IsValidString())
{
inputString.SaveToFile();
}
else
{
MessageBox.Show("The input string is not valid: please insert a valid string",
"Empty or null input string",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tbInputText.Focus();
}
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
List<string> textFileContent = new List<string>();
textFileContent = openFile.OpenTextFile(); // Open Text File via openFile variable
tbFileText.Text = string.Join(Environment.NewLine, textFileContent);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (File.Exists(openFile.fileName)) // Validate file exists via openFile.fileName property
{
List<string> textReadFromFile = new List<string>();
textReadFromFile = File.ReadAllLines(fileName).ToList();
tbFileText.Text = string.Join(Environment.NewLine, textReadFromFile);
}
}
}
}
You can also reduce your code by changing your IsValidString method to an extension method
public static bool IsValidString(this string stringToValidate) => !string.IsNullOrEmpty(stringToValidate)
I would recommend somewhat redesigning the code because there are potential bugs waiting to be found by using one class, I.E OpenFile, for opening and checking file contents. What if the file isn't opened and fileName is an empty string for example.
See the following MSDN article on classes to understand them more in-depth, and how the interact with each other.
Refactored Code
I have refactored the code to make it a bit more manageable and readable, please see below.
Here's a new class called TextFile which you can store the filename and contents in.
namespace ProvaSalvataggioFile2
{
public class TextFile
{
public TextFile(string fileName, string contents)
{
FileName = fileName;
Contents = contents;
}
public string FileName { get; set; }
public string Contents { get; set; }
}
}
Your OpenFile class is actually named pretty well, it has quite a good separation of concerns - meaning that on first glance I can see that it's a class which should only be used to open files, though you could go a step further and abstract the UI code away which couples you to Win Forms. OpenTextFile now returns a TextFile object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public class OpenFile
{
public TextFile OpenTextFile()
{
TextFile textFile;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.CheckPathExists = true;
openFileDialog1.CheckFileExists = true;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog1.FileName.ToString();
string textReadFromFile = File.ReadAllText(openFileDialog1.FileName);
textFile = new TextFile(fileName, textReadFromFile);
}
return textFile;
}
}
}
And of course, MainForm has to be updated to take the new object into consideration, I've removed duplicated code, reused your OpenFile class and introduced a RefreshTextFile method for setting the label text - this time you don't have to worry about file names being valid.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public partial class MainForm : Form
{
private readonly OpenFile openFile = new OpenFile();
public MainForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string inputString = tbInputText.Text;
if (inputString.IsValidString())
{
inputString.SaveToFile();
}
else
{
MessageBox.Show("The input string is not valid: please insert a valid string",
"Empty or null input string",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tbInputText.Focus();
}
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
RefreshTextFile();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
RefreshTextFile();
}
private void RefreshTextFile()
{
TextFile textFile = openFile.OpenTextFile();
tbFileText.Text = textFile?.Contents;
}
}
}
Please note I have refactored this using Notepad++ and haven't put it through a compiler.
Your Form class doesn't know where or what OpenTextFile() is, same goes for fileName.
You need to create an instance of the object you want to use.
Try adding this code to MainForm:
private OpenFile _openFile;
public MainForm()
{
this._openFile = new OpenFile();
InitializeComponent();
}
This creates a new instance of the OpenFile class that MainForm can now use.
You can also make OpenFile static but that is not considered to be a best practice.
Please note that since your OpenFile.fileName is not initialized that you might want to add something like this as well.
public OpenFile(string initialFileName = "defaultFilename"){
this.fileName = initialFileName;
}
you can then even specify the filename in MainForm by providing it as an argument.
Or if you don't want to set an argument you can do a null check before reading/using the fileName.
for more info about objects and constructor see:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/objects
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors
so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.
There are two classes, one to cover the form (class 1) and the other to cover what gets displayed on the form (class 2). I'm trying to call a method in class 1 from class 2 to display certain information in a text box. I keep getting the error:
An object reference is required for the non-static field, method, or property
I've encountered this error before and been able to make it through, but nothing I've attempted so far has helped in this instance. I'm posting code for both the classes.
Class 1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
namespace Project6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
//Create an instance of the open file dialog box
OpenFileDialog ofd = new OpenFileDialog();
//Set parameters, filter options, and filter index
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Text Files (.txt)|*.txt";
ofd.FilterIndex = 2;
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = ofd.OpenFile()) != null)
{
using (myStream = ofd.OpenFile())
{
StreamReader reader = new StreamReader(myStream);
string studentInformation = "";
string[] studentInformationArray = new string[11];
studentInformation = reader.ReadLine();
while ((studentInformation = reader.ReadLine()) != null)
{
studentInformationArray = studentInformation.Split(',');
Student newStudent = new Student(studentInformationArray);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = Student.GetName(); //This generates the compiler error
textBox1.Select(6, 5);
MessageBox.Show(textBox1.SelectedText);
}
}
}
Class 2:
using System;
using System.Windows.Forms;
namespace Project6
{
class Student
{
//Initialize variables
private string[] studentInformationArray;
//Constructor that accepts the studentInformationArray as an argument
public Student(string[] studentInformationArray)
{
this.studentInformationArray = studentInformationArray;
}
public Student()
{
string className = studentInformationArray[1];
string semester = studentInformationArray[2];
string picture = studentInformationArray[3];
int project1 = Convert.ToInt32(studentInformationArray[4]);
int project2 = Convert.ToInt32(studentInformationArray[5]);
int project3 = Convert.ToInt32(studentInformationArray[6]);
int project4 = Convert.ToInt32(studentInformationArray[7]);
int project5 = Convert.ToInt32(studentInformationArray[8]);
int project6 = Convert.ToInt32(studentInformationArray[9]);
int midtermExam = Convert.ToInt32(studentInformationArray[10]);
int finalExam = Convert.ToInt32(studentInformationArray[11]);
}
public string GetName()
{
string studentName;
studentName = studentInformationArray[0];
return studentName;
}
}
}
That's because that's not how you use the OpenFileDialog. Take a look at this example hosted by the MSDN here:
Edit: answering to your edited question. You will always get a NullReferenceException in the Student() constructor because you are never assigning something to your studentInformationArray. So you can fix it like this:
public Student()
{
studentInformationArray = new studentInformationArray[12];
string className = studentInformationArray[1];
// rest of your code...
}
However, you should take into account that studentInformationArray will be an empty array unless you assign something to it. Since you have a Student() overload that takes a string[], I'd suggest you that you either remove the default constructor or make it call the overloaded with default information, like this:
public Student(string[] studentInformationArray)
{
string className = studentInformationArray[1];
// rest of your code...
int project1 = int.Parse(studentInformationArray[4]); // always prefer int.Parse() instead of Convert.ToInt32()
// rest of your code...
this.studentInformationArray = studentInformationArray;
}
public Student()
{
string[] defaultInformation = new string[12];
// add information
defaultInformation[0] = "some information";
// ...
new Student(defaultInformation);
}
Some more points to take into account:
Class-level fields/properties should be spelled in Pascal Case (first letter of each word in uppercase, rest in lowercase)
Try to never use this.variableName = variableName.
Variables names should never include the type of the variable, that's redundant.
So, for example, change this:
private string[] studentInformationArray;
for this:
private string[] StudentInformation;
Answering your last question, regarding the compiler error, you need a reference to the Student read in order to get its name. You could do something like this:
public partial class Form1 : Form
{
private Student StudentRead;
// rest of your code...
// from your read method:
StudentRead = new Student(studentInformationArray);
// and finally:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = StudentRead.GetName();
I need to compare a name of an object (test) with the name of a test that has been placed into a queue. The logic I have is to use a foreach loop so that for each test in the queue I can compare the name that the user provides with the name on each test until it finds a match (in which it will tell the user the score they made on the test in a message box).
The code in the snippet is incomplete; using submittedTests with a getter doesn't work (doesn't give me an option to do so in intellisense).
This takes place in the btnFindTest_Click method. This is the code that I have so far:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication1
{
public partial class Form1 : Form
{
//Stack and Queue calls
Queue submittedTest = new Queue();
Stack outForChecking = new Stack();
public Form1()
{
InitializeComponent();
}
private void btnSubmitTest_Click(object sender, EventArgs e)
{
//generates a random test score
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
//assigns user input to a variable
string name = txtName.Text;
//Generate a new test that passes in
Test tests = new Test(name, score);
//shows the user the name they just enetered
label3.Text = String.Format("{0}", name);
//adds submitted test to the queue, then displays that test in a list box
submittedTest.Enqueue(tests);
listSubTests.Items.Add(new Test(name, score));
//Clears input box for next user input
txtName.Clear();
}
private void btnFindTest_Click(object sender, EventArgs e)
{
string compareName = "";
string tempName = txtName.Text;
foreach (Test tests in submittedTest)
{
if (compareName == tempName)
{
System.Windows.Forms.MessageBox.Show("Your score was --");
}
}
}
public void txtName_TextChanged(object sender, EventArgs e)
{
}
private void txtScore_TextChanged(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
}
}
And the test object is defined in it's own class here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private string name;
private string score;
public string Name
{
get { return name; }
set { name = value; }
}
public string Score
{
get { return score; }
set { score = value; }
}
public Test(string name, string score)
{
this.name = name;
this.score = score;
}
public override string ToString()
{
return (String.Format("{0} {1} ", name, score));
}
}
}
I'm reletively new to C# and this project is for school, so if I'm far off, please let me know!
Based on your example, you may have forgotten to use the object:
foreach (Test tests in submittedTest)
{
if (tests.Name == tempName)
{
System.Windows.Forms.MessageBox.Show("Your score was --");
}
}