How to print just value to label from textbox in winforms? - c#

I'm writing a name generator, and want to add functionality to add new names and surnames to database, but when I'm trying to print values added after running program, I got whole path. For example: I want to add name John. When generator picks John it's printing Windows.Forms.TextBox, Text:John instead of just name. How can I fix this? Here's the code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace NameGen
{
public partial class Form1 : Form
{
public Generate gen = new Generate();
public Form1()
{
InitializeComponent();
}
private void StartGenerate(object sender, EventArgs e)
{
lblWynik.Text = Generate.NameGen() + " " + Generate.SurnameGen();
Console.WriteLine("Generating: " + lblWynik.Text);
}
private void AddName(object sender, EventArgs e)
{
Generate.LName.Add(NameBox.ToString());
Console.WriteLine("Adding new name to index " + NameBox);
NameBox.Clear();
}
private void AddSurname(object sender, EventArgs e)
{
Generate.LSurname.Add(SurnameBox.ToString());
Console.WriteLine("Adding new surname to index " + SurnameBox);
SurnameBox.Clear();
}
}
public class Generate
{
static string[] Name = new string[] { "Hank", "Terrence", "Darin", "Alf" };
static string[] Surname = new string[] { "Cooper", "Trump", "Białkov", "Obama" };
public static List<string> LName = new List<string>();
public static List<string> LSurname = new List<string>();
static Random random = new Random();
public static string NameGen()
{
LName.AddRange(Name);
int NameIndex = random.Next(LName.Count);
return LName[NameIndex];
}
public static string SurnameGen()
{
LSurname.AddRange(Surname);
int NameIndex = random.Next(LSurname.Count);
return LSurname[NameIndex];
}
}

To get the text of a TextBox you should use Text property of TextBox. For example: Generate.LName.Add(NameBox.Text);
Now you are using ToString method of TextBox which returns the type name and the text.

Related

ListBoxes won't display data from StreamReader text files

I have the .txt files inside the project's debug folder but the listboxes still won't display any of the data.
I've already missed the due date for this project, I just have a very unhelpful professor and I'd love to learn what I did wrong. Thanks!
The overview of what I'm trying to do here is:
Display delimited data into three listboxes from three text files. When a user clicks on an item in the listbox, one line of additional data (an ID) will be displayed in a textbox underneath that listbox. All three listboxes are shown on the same form and all data is delimited using the same character.
Here is my 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 LabDay2Modified
{
struct CustomersNames
{
public string custID;
public string firstName;
public string lastName;
public string accountID;
}
struct AccountNumbers
{
public string acctID;
public string accountType;
public string accountNumber;
public string accountAmt;
}
struct LoanInfo
{
public string loanID;
public string loanYears;
public string loanIntRate;
public string loanAmt;
public string customerID;
public string loanType;
}
public partial class Form1 : Form
{
private List<CustomersNames> customerList = new List<CustomersNames>();
private List<AccountNumbers> accountList = new List<AccountNumbers>();
private List<LoanInfo> loanList = new List<LoanInfo>();
public Form1()
{
InitializeComponent();
}
private void ReadCustFile()
{
try
{
StreamReader inputFile;
string line;
CustomersNames entry = new CustomersNames();
char[] delim = { ',' };
inputFile = File.OpenText("customers.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.custID = tokens[0];
entry.firstName = tokens[1];
entry.lastName = tokens[2];
entry.accountID = tokens[3];
customerList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadAcctFile()
{
try
{
StreamReader inputFile;
string line;
AccountNumbers entry = new AccountNumbers();
char[] delim = { ',' };
inputFile = File.OpenText("accounts.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.acctID = tokens[0];
entry.accountNumber = tokens[1];
entry.accountType = tokens[2];
entry.accountAmt = tokens[3];
accountList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadLoanFile()
{
try
{
StreamReader inputFile;
string line;
LoanInfo entry = new LoanInfo();
char[] delim = { ',' };
inputFile = File.OpenText("loans.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.customerID = tokens[0];
entry.loanID = tokens[1];
entry.loanType = tokens[2];
entry.loanYears = tokens[3];
entry.loanIntRate = tokens[4];
entry.loanAmt = tokens[5];
loanList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CustInfo()
{
foreach(CustomersNames entry in customerList)
{
customerListBox.Items.Add(entry.custID + " " + entry.firstName + " " + entry.lastName);
}
}
private void AcctInfo()
{
foreach (AccountNumbers entry in accountList)
{
accountListBox.Items.Add(entry.accountNumber + " " + entry.accountType + " " + entry.accountAmt);
}
}
private void LoansInfo()
{
foreach (LoanInfo entry in loanList)
{
loanListBox.Items.Add(entry.loanID + " " + entry.loanType + " " + entry.loanYears+" "+entry.loanIntRate+" "+entry.loanAmt);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void customerListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = customerListBox.SelectedIndex;
customerAccountID.Text = "Account ID: " + customerList[index].accountID;
}
private void loanListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = loanListBox.SelectedIndex;
loanCustomerID.Text = "Customer ID: " + loanList[index].customerID;
}
private void accountListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = accountListBox.SelectedIndex;
accountAccountID.Text = "Account ID: " + accountList[index].acctID;
}
private void Form1_Load(object sender, EventArgs e)
{
ReadCustFile();
CustInfo();
ReadAcctFile();
AcctInfo();
ReadLoanFile();
LoansInfo();
}
}
}
You can use the following .txt file to see if it works for you.
Then, you will get the following result.
Besides, you can set the similar style for other txt files.

MessageBox doesn't show the variable

I have a list variable and I created an iterator for it to print out its content. It's working in the console application but when i try to do it using windows form(gui) it doesn't work
PROGRAM.CS
namespace gui
{
static class Program
{
public class studentdata
{
public string id, name, password, academicyear, finishedcourseslist, ipcourseslist;
public int noCoursesF, noCoursesIP;
public List<string> coursesF;
public List<string> coursesIP;
public studentdata()
{
id = "2015123";
password = "Student";
coursesF = new List<string>();
coursesIP = new List<string>();
}
public studentdata(string ID, string NAME, string PASSWORD)
{
id = ID;
}
**public void view_finished_courses()
{
List<string> finished = coursesF;
foreach (string n in finished)
{
finishedcourseslist += n;
}
MessageBox.Show(finishedcourseslist, "Finished courses");
}
public void view_ip_courses()
{
List<string> progress = coursesIP;
foreach (string m in progress)
{
ipcourseslist += m;
}
MessageBox.Show(ipcourseslist, "Finished courses");
}**
}
public class Admin
{
public string name, password;
public Admin()
{
name = "Admin";
password = "Admin";
}
}
//functionssssss
internal static studentdata studentSearch(string IDsearch)
{
FileStream FS = new FileStream("Students.txt", FileMode.Open);
StreamReader SR = new StreamReader(FS);
studentdata std = new studentdata();
while (SR.Peek() != -1)
{
string z = SR.ReadLine();
String[] Fields;
Fields = z.Split(',');
if (IDsearch.CompareTo(Fields[0]) == 0)
{
std.id = Fields[0];
std.password = Fields[1];
std.name = Fields[2];
std.noCoursesF = int.Parse(Fields[3]);
int currentField = 4;
for (int course = 0; course < std.noCoursesF; course++)
{
std.coursesF.Add(Fields[currentField]);
currentField++;
}
std.noCoursesIP = int.Parse(Fields[currentField]);
currentField++;
for (int course = 0; course < std.noCoursesIP; course++)
{
std.coursesIP.Add(Fields[currentField]);
currentField++;
}
std.academicyear = Fields[currentField];
SR.Close();
return std;
}
else continue;
}
SR.Close();
studentdata araf = new studentdata();
return araf;
}
}
FORM.CS
namespace gui
{
public partial class Form3 : Form
{
Program.studentdata student = new Program.studentdata();
public Form3()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
student.view_finished_courses();
}
private void button6_Click(object sender, EventArgs e)
{
student.view_ip_courses();
}
}
}
The output is an empty message box, I don't know why variable isn't added.
Replace messagebox line with
MessageBox.Show(string.Join(",", coursesF.ToArray()), "Finished courses");
It seems like your code is incomplete. Nowhere in the code which gets executed after you clicked button4 you are adding items to coursesF. It seems that you are adding items in this line: std.coursesF.Add(Fields[currentField]);
This line is in your function studentSearch(IDsearch), the function never gets called.
In this function you got a string z in which all the data of a student is saved (string z = SR.ReadLine()). You must somehow fill this string z. You can use a TextBox in your form and pass the value into the string, use a string from a text file or use the console input(see here: Get input from console into a form).
As you can see the issue is not a one line fix.

Adding multiple values to arraylist from user input

I'm new to C# and I just have a quick question about adding to an array list. I have an arraylist which shows some details about different books (Name, Genre, Author and Year Published). How can I make it so that a user can input all these values (name, genre, etc) into multiple textboxes and then click a button to add all the details as a new book in the list?
Below is my code so far:
namespace LibraryBooks
{
public partial class Form1 : Form
{
List<Object> library = new List<Object>();
int current = 0;
public Form1()
{
InitializeComponent();
InitializeArrayList();
DisplayData();
}
public void DisplayData()
{
Books b = (Books)library[current];
textBox1.Text = "" + b.readTitle();
textBox2.Text = "" + b.readGenre();
textBox3.Text = "" + b.readAuthor();
textBox4.Text = "" + b.readYearPublished();
}
public void InitializeArrayList()
{
library.Add(new Books("The Hunger Games", "Adventure", "Suzanne Collins", "2008"));
library.Add(new Books("Gone Girl", "Thriller", "Gillian Flynn", "2014"));
library.Add(new Books("A Game of Thrones", "Fantasy", "George R.R. Martin", "1996"));
}
private void button5_Click(object sender, EventArgs e)
{
if (movies.Contains(textBox7.Text))
{
textBox1.Text = "";
}
}
}
public class Test92
{
public static void Main(string[] args)
{
Application.Run(new Form1());
}
}
}
I'm not sure how to go about it at all so any ideas would be appreciated.
It's very simple. Create all the textboxes you need for each input, and then in your button_click method, write something along the lines of
library.Add(new Books(textbox1.text, textbox2.text, textbox3.text));
This functions very similarly to what your InitializeArrayList method does, but instead of passing pre-determined text to your Books constructor, it takes in text from the textboxes on your form.

Solve recursion and infinite loop issue

I am currently writing a program which reads data in from a text file. The problem I am currently having is that the CompareTo method below is coming up with the error System.StackOverflowException was unhandled and saying "Make sure you don't have an infinite loop or infinite recursion. This error appears on the line return name.CompareTo(temp.name);.
The whole class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Country
{
public class Country : IComparable
{
// Country Properties
private String name;
private float gdpGrowth;
private float inflation;
private float tradeBalance;
private float hdiRanking;
private LinkedList<String> tradePartners;
//Constructor
public Country(String name, float gdpGrowth, float inflation, float tradeBalance, float hdiRanking, LinkedList<String> tradePartners)
{
this.name = name;
this.gdpGrowth = gdpGrowth;
this.inflation = inflation;
this.tradeBalance = tradeBalance;
this.hdiRanking = hdiRanking;
this.tradePartners = tradePartners;
}
public String Name
{
set { this.name = value; }
get { return name; }
}
public float GdpGrowth
{
set { this.gdpGrowth = value; }
get { return gdpGrowth; }
}
public float Inflation
{
set { this.inflation = value; }
get { return inflation; }
}
public float TradeBalance
{
set { this.tradeBalance = value; }
get { return tradeBalance; }
}
public float HdiRankings
{
set { this.hdiRanking = value; }
get { return hdiRanking; }
}
public LinkedList<String> TradePartners
{
set { this.tradePartners = value; }
get { return tradePartners; }
}
public override string ToString()
{
return name + ", " + gdpGrowth + ", " + inflation + ", " + tradeBalance + ", " + hdiRanking + ", " + tradePartners;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return name.CompareTo(temp.name);
}
}
}
The class which is calling the country class is...
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 Country
{
public partial class Form1 : Form
{
private AVLTree<Country> countryTree = new AVLTree<Country>();
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// array to stroe each line of the file
String[] Lines = new string[1000];
String[] tempPartners = new string[1000];
int count = 0;
// Store each line of the file in the eachLine array
Lines = File.ReadAllLines("countries.csv");
foreach (String line in Lines)
{
if (count == 0)
{
count++;
}
else
{
// array to hold info
String[] info = new string[5];
//splits the countries
info = line.Split(',');
// split trade partners and puts in array
tempPartners = info[5].Split(';', '[', ']');
// insert current instance of country into AVL Tree
countryTree.InsertItem(new Country(info[0], float.Parse(info[1]),
float.Parse(info[2]), float.Parse(info[3]), float.Parse(info[4]), new LinkedList<String>(tempPartners)));
// create seperator
string seperator = ", ";
// stroe array
string partners = string.Join(seperator, tempPartners);
// remove first comma
partners = partners.Substring(1, partners.Length - 1);
//remove last comma
partners = partners.Remove(partners.Length - 2);
//pass in information from file into grid view
dataGridView1.Rows.Add(info[0], info[1], info[2], info[3], info[4], partners);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You've got infinite recursion going here. CompareTo makes a recursive call but doesn't terminate due to the lack of a base case, so the recursive stack grows infinite. No actual comparison takes place either. What integer values do you want this to return, and under what conditions?
Perhaps as CyberDude said, you're really trying to use String.Compare(name, temp.name)?

Assigned values to a variable in a class from Button click event outside. But returning zero as output from another button click

Here I have a variable in a class and trying to give input and get output from through buttons outside the class. But when I am creating new object to a class (button2), I am not getting output values given (button1).
class dataconversion
{
public List<decimal> sample = new List<decimal>();
public void dataconvert(List <decimal> transfer)
{
string filedata;
Stream filestream;
OpenFileDialog opendialog = new OpenFileDialog();
if (opendialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((filestream = opendialog.OpenFile()) != null)
{
filedata = System.IO.File.ReadAllText(opendialog.FileName);
List<string> stringlist = new List<string>(filedata.Split(' ', '\n', '\t'));
stringlist = stringlist.Where(val => val != "").ToList();
List<decimal> decimallist = stringlist.ConvertAll(s => decimal.Parse(s));
transfer.AddRange(decimallist);
}
}
}
}
public class methodacess
{
dataconversion dc = new dataconversion();
public void sampleaccess()
{
dc.dataconvert(dc.sample);
}
public void messages()
{
MessageBox.Show(dc.sample.Count.ToString());
}
//output is giving only zeros.
}
private void button1_Click(object sender, EventArgs e)
{
methodacess ma = new methodacess();
ma.sampleaccess();
}
private void button4_Click(object sender, EventArgs e)
{
methodacess ma4 = new methodacess();
ma4.messages();
}
}
Your problem is this line in button4_Click:
methodacess ma4 = new methodacess();
You are creating a brand new instance of methodacess.
In fact the one you created in button1_Click is not stored anywhere and is lost after the method exits.
So your call to ma.sampleaccess(); is on a different instance to the call on ma4.messages(); so no wonder there is no data.
Now, I don't like the way you've structured your classes. It's really a bit odd, but sticking with this structure here's how I would write it.
First, dataconversion - make it static with a single function that returns a new copy of the list.
public static class dataconversion
{
public static List<decimal> dataconvert()
{
var filedata = "";
using (var opendialog = new OpenFileDialog())
{
if (opendialog.ShowDialog() == DialogResult.OK)
{
if (System.IO.File.Exists(opendialog.FileName))
{
filedata = System.IO.File.ReadAllText(opendialog.FileName);
}
}
}
return
filedata
.Split(' ', '\n', '\t')
.Where(val => val != "")
.Select(s => decimal.Parse(s))
.ToList();
}
}
Now, methodaccess - notice it now just holds the actual list of decimals:
public class methodacess
{
List<decimal> data = new List<decimal>();
public void sampleaccess()
{
data = dataconversion.dataconvert();
}
public void messages()
{
MessageBox.Show(data.Count.ToString());
}
}
And finally your UI calling code:
private methodacess ma = new methodacess();
private void button1_Click(object sender, EventArgs e)
{
ma.sampleaccess();
}
private void button4_Click(object sender, EventArgs e)
{
ma.messages();
}
Note that there is a single instance of methodaccess.

Categories