C# Forms add text to textbox from other class - c#

I have a C# Form called Form1.cs and a Class in the same project called RandWord.cs.
Now I want to add text to the textbox (tbRandom) from the class.
I added the following code to Form1.cs:
public TextBox tbRandom;
And the following code to the class:
public RandWord()
{
//get linecount
int linesGerman = File.ReadAllLines(pathGerman).Length;
int linesFrance = File.ReadAllLines(pathFrance).Length;
//check if same linecount
if (linesGerman == linesFrance)
{
//new random int
Random rnd = new Random();
int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length);
//write to Form1's Textbox tbWord
f1.tbRandom.Text = rndLine.ToString();
MessageBox.Show(rndLine.ToString());
}
}
The messagebox is just there to prove that the Int is not empty. But the textbox won't display anything. There is no Exception aswell. The class is called by a button ( RandWord(); )
Any ideas?

In you From1 :
public TextBox tbRandom =new TextBox() ;
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(tbRandom);
}
public string TextBoxTxt {
get { return txtText1.Text; }
set { txtText1.Text = value; }
}
//Your button RandWord
private void RandWord_Click(object sender, EventArgs e)
{
RandWord(this);
}
Your class RandWord :
public RandWord(Form f1)
{
//get linecount
int linesGerman = File.ReadAllLines(pathGerman).Length;
int linesFrance = File.ReadAllLines(pathFrance).Length;
//check if same linecount
if (linesGerman == linesFrance)
{
//new random int
Random rnd = new Random();
int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length);
//write to Form1's Textbox tbWord
f1.TextBoxTxt = rndLine.ToString();
MessageBox.Show(rndLine.ToString());
}
}

You can write a contractor method for your class and pass the TextBox to it, and you can access the TextBox from there.
class GenerateRandomWord
{
TextBox _t;
public GenerateRandomWord(TextBox t)
{
_t = t;
}
public void RandWord()
{
_t.Text = "Something!";
}
}

Related

How to bind an object to the label in c# windows forms

I have labels with footballer's names inside. I want to get footballer's age after clicking on these labels. I do it by this way:
public partial class Form1 : Form
{
Footballer[] team = { /*team initialization*/};
public Form1()
{
InitializeComponent();
}
private void OnLabel_Click(object sender, EventArgs e)
{
for (int i = 0; i < team.Length; i++)
{
if (team[i].Name == this.Text)
{
MessageBox.Show(team[i].Age.ToString());
break;
}
}
}
}
But there is problem. There might be more than one player with the same name. So I want to bind each label with footballer. How can I do this?
For sake of simplicity suppose that you initialize your labels in this mode....
public Form1()
{
InitializeComponent();
int index = 0;
foreach(Label lbl in this.Controls.OfType<Label>())
{
lbl.Text = team[index].Name;
// Make the Tag property reference the Footballer instance
// used to set the label text with the footballer name
lbl.Tag = team[index];
index++;
}
At this point, when you receive the click event, you just need to retrieve the reference from the Tag property and use it directly
private void OnLabel_Click(object sender, EventArgs e)
{
// No loop needed here
Label current = sender as Label;
Footballer player = current.Tag as Footballer;
if(player != null)
MessageBox.Show(player.Age.ToString());
}
}
You should separate out your business logic from your presentation logic. The name is what you presented, but to keep each player/team unique then assign a unique ID.
This is then assigned to the label but hidden from view, so that when the label is clicked the ID is retrieved and you can then do a lookup based on this.
So with Player class like the following:
public class Player
{
public int ID { get;set; }
public string Name { get;set; }
//etc.
}
Then when assigning a Player to label use Label.Tag which is a general purpose field which you can use for anything your want. (Available on all Controls).
label1.Text = MyPlayer.Name;
label1.Tag = MyPlayer.ID;
If I was you, I would also change your Teams to be a List not an array
List<Footballer> team = new List<Footballer>() { /*team initialization*/};
Then you can look up as follows
private void OnLabel_Click(object sender, EventArgs e)
{
Label clickedLabel = (sender as Label);
int id = Convert.ToInt32(clickedLabel.Tag);
Footballer found = team.Find(x => x.Id == id);
MessageBox.Show(found.Age.ToString());
}

Update data in a listbox from another form

I'm creating a program that maintains student scores. I've created a class called students that stores the data and displays it in a list box. Once the user clicks Add a new form (frmAddStudent) loads that allow them to add the user by name and their scores and display it in the list box in the main form. It also allows the update/delete functions. I can successfully add students to the list and edit them, but when I press the ok button in the update students form I get the error
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
I looked up that this means its thrown when the value of an argument is outside the allowable range of values as defined by the invoked method, but not sure how it applies here. My value I enter when updating is within range.
Source code below
https://github.com/Triptonix/Student.git
frmUpdateStudent.cs
private void UpdateButton_Click_1(object sender, EventArgs e) //open update form for current student
{
Student Form1 = new Student();
Form1.Name = StudentName.Text;
parentForm.UpdateStudent(index, Form1);
Close();
}
Form1.cs
public List<Student> studentList = new List<Student>();
public Student GetStudent(int id) //Get student index
{
return studentList[id];
}
public void UpdateStudentList()
{
students.DataSource = null;
students.DataSource = studentList;
students.DisplayMember = "Name";
}
public bool UpdateStudent(int originalIndex, Student studentToEdit)
{
try
{
Student student = GetStudent(originalIndex); //select index of student
student.Name = studentToEdit.Name; //name of student
studentList.RemoveAt(originalIndex); //remove the student at the index selected
studentList.Insert(originalIndex, student); //insert new student at index.
UpdateStudentList(); //update student list
}
catch { return false; }
return true;
}
Student.cs
public class Student
{
public List<int> Scores = new List<int>();
public string Name { get; set; }
public bool AddScore(int score)
{
try
{
Scores.Add(score);
}
catch { return false; }
return true;
}
public List<int> GetScores()
{
return Scores;
}
public int GetScoreAt(int index)
{
return (int)Scores[index];
}
public int GetScoreTotal()
{
int sum = 0;
foreach (int score in Scores)
{
sum += score;
}
return sum;
}
public int GetScoreCount()
{
return Scores.Count;
}
public int GetScoreAverage()
{
return GetScoreTotal() / GetScoreCount();
}
public void DestroyScores()
{
Scores = new List<int>();
}
}
frmUpdateStudent
public partial class frmUpdateStudent : Form
{
private Form1 parentForm; //main form
private Student studentToEdit; //student list
private int index; //index
public frmUpdateStudent(Form1 parentForm, int index) //update parent form (Form1) with the new student and scores
{
this.parentForm = parentForm;
this.index = index;
studentToEdit = this.parentForm.GetStudent(index);
InitializeComponent();
StudentName.Text = studentToEdit.Name;
UpdateScoreDisplay();
}
public void AddScoreToStudent(int value) //add score to current student and display in the list
{
studentToEdit.AddScore(value);
UpdateScoreDisplay();
}
public void UpdateScoreAtIndex(int id, int value) //update a score selected from the list
{
studentToEdit.GetScores()[id] = value;
UpdateScoreDisplay();
}
public int GetScoreAtIndex(int id) //get the score index
{
return studentToEdit.GetScoreAt(id);
}
private void UpdateScoreDisplay() //update the score display list
{
CurrentScores.DataSource = null;
CurrentScores.DataSource = studentToEdit.GetScores();
}
private void AddScoreButton_Click(object sender, EventArgs e) //open the add score form
{
frmAddScore addScoreForm = new frmAddScore(this);
addScoreForm.Show();
}
private void RemoveScoreButton_Click_1(object sender, EventArgs e) //remove a score from current index and update display list
{
studentToEdit.GetScores().RemoveAt(CurrentScores.SelectedIndex);
UpdateScoreDisplay();
}
private void ClearScoresButton_Click_1(object sender, EventArgs e) //clear all scores
{
studentToEdit.DestroyScores();
UpdateScoreDisplay();
}
private void CloseButton_Click_1(object sender, EventArgs e)
{
Close(); //close form
}
private void UpdateButton_Click_1(object sender, EventArgs e) //open update form for current student
{
Student Form1 = new Student();
Form1.Name = StudentName.Text;
parentForm.UpdateStudent(index, Form1);
Close();
}
private void UpdateScoresButton_Click(object sender, EventArgs e)
{
frmUpdateScore updateScoreForm = new frmUpdateScore(this, CurrentScores.SelectedIndex);
updateScoreForm.Show();
}
}
So turns out the index of my list was -1 when I was trying to call it. I set the SelectedIndex as a local variable then called it. I guess the selected index had to be checked before I could execute it. This the code I fixed.
private void students_SelectedIndexChanged_1(object sender, EventArgs e) {
_selectedIndex = students.SelectedIndex;
if (_selectedIndex > -1)
{
Student student = GetStudent(_selectedIndex); //select index from list
Student students = GetStudent(_selectedIndex); //select index from list
ScoreTotalTextBox.Text = student.GetScoreTotal().ToString(); //show Score Total to box
ScoreCountTextBox.Text = student.GetScoreCount().ToString(); //show Score Count to box
ScoreAverageTextBox.Text = student.GetScoreAverage().ToString(); //show Score Average to box
}
}

USer Control Custom event and set get property

I have 2 labels and a property in user control:
Here is property:
private int _SelectIndex;
[Browsable(true)]
public int SelectIndex { get; set; }
and 2 labels:
Label lbl1, lbl2;
void iControl()
{
lbl1 = new Label();
lbl2 = new Label();
lbl1.Name = "lbl1";
lbl2.Name = "lbl2";
lbl1.Click += lbl_Click;
lbl2.Click += lbl_Click;
this.Controls.Add(lbl1);
this.Controls.Add(lbl2);
}
Click:
void lbl_Click(object sender, EventArgs e)
{
Label selectedlbl = sender as Label;
if(selectedlbl.Name == "lbl1")
this.Select = 1;
else
this.Select = 2;
}
Class Event:
public class SelectEventArgs : EventArgs
{
private int index;
public SelectEventArgs(int index)
{
this.index = index;
}
public int ItemIndex
{
get
{
return index;
}
}
}
Custom event in my control:
public event EventHandler SelectEvent;
protected virtual void OnSelectEvent()
{
if (SelectEvent!= null)
SelectEvent(this, new SelectEventArgs(this._SelectIndex));
}
I need an event to get and set property value in MainForm as following:
int index = 0;
public Form1()
{
InitializeComponent();
this.icontrol = new iControl();
this.SelectEvent += Select();
}
void Select(object sender, SelectItem e)
{
//use this to set value of Select
this.icontrol.SelectIndex = index;
//and this to get value of Select
index = this.icontrol.SelectIndex;
}
Select is empty.
How to get it to work?
I post here for any one need it:
1.Declare a delegate:
public delegate void SelectIndexEventHandler(object sender, SelectEventArgs e);
public class SelectEventArgs : EventArgs
{
private int index;
public SelectEventArgs(int index)
{
this.index = index;
}
public int ItemIndex
{
get { return index; }
set { index = value; }
}
}
2. declare an event SelectIndexChanged and a method OnSelectIndexChanged:
public event SelectIndexEventHandler SelectIndexChanged;
protected virtual void OnSelectIndexChanged(SelectEventArgs e)
{
if (SelectIndexChanged != null)
SelectIndexChanged(this, e);
}
3.Call it in setter:
public int SelectIndex
{
get { return _SelectIndex; }
set {
_SelectIndex = value;
OnSelectIndexChanged(new SelectEventArgs(value));
}
}
and then MainForm:
this.gListBox1.SelectIndexChanged += icontrol_SelectIndexChanged;
void icontrol_SelectIndexChanged(object sender, SelectEventArgs e)
{
var current = e.ItemIndex;
}
thank again jbmintjb Reza Aghaei.
The code has multiple issues. Consider these tips to solve the issues:
SelecetEvent does't belong to the Form. The event belongs to icontrol.
this.SelectEvent += Select(); is incorrect, you should use:
icontrol.SelectEvent += Select;
When you have a custom event args, you should define the event this way:
public event EventHandler<SelectEventArgs> SelectEvent;
You should raise the event in setter of your property, using OnSelectEvent method which you created.
To learn more about events take a look at C# Handling and Raising Events.
Take a look at the SelectedIndexChanged event on the listbox control, think that is what you are looking for

When trying to add a value it just gives the new value C#

I am making a banking ap that keeps track off the amount of money someone has in the bank (called Saldo)
So i created a constuctor that assigns a name to a account and this keeps track of everys person balance
however in my current code i can only add money once and when i change the input it automatically changes to that and doesnt add or subtract (what it is suposed to do)
the important parts of the code are
private void StortL_Click(object sender, EventArgs e)
{
Bankrekening BankrekeningL = new Bankrekening(bankrekeningLinks.Naam, 0);
double saldodouble = 0;
int bedrag = 0;
int decimalL = 0;
int wholeL = 0;
decimalL = Convert.ToInt32(tbDecimaleL.Text);
wholeL = Convert.ToInt32(tbWholeL.Text) * 100;
bedrag = wholeL + decimalL;
Bankrekening BankrekeningL2 = new Bankrekening(bankrekeningLinks.Naam, BankrekeningL.Saldo);
BankrekeningL2.Stort(bedrag);
lbIsaldoL.Text = Convert.ToString(BankrekeningL2.Saldo);
}
}
}
And
class Bankrekening
{
//datavelden
private int rekeningnummer;
private string naam;
private int saldo;
private static int volgendeVrijeRekeningnummer = 2001;
//properties
public int Rekeningnummer { get { return rekeningnummer; } }
public string Naam { get { return naam; } }
public int Saldo { get { return saldo; } }
//constructors
public Bankrekening(string naam)
{
this.naam = naam;
saldo = 0;
//volgendeVrijeRekeningnummer is klassevariable,
//je kunt this niet gebruiken
rekeningnummer = volgendeVrijeRekeningnummer++;
}
public Bankrekening(string naam, int saldo)
{
this.naam = naam;
this.saldo = saldo;
}
public void NeemOp(int bedrag)
{
saldo = saldo+bedrag;
}
public void Stort(int bedrag)
{
saldo = saldo + bedrag;
}
public void MaakOverNaar(Bankrekening andereRekening, int bedrag)
{
//zelf invullen
}
}
So what currently is happening is that instead of adding the number in a text box to the value of saldo (the previous inputs of the text box) it just sets the value of saldo to the value of whatever is in the text box.
E.G. i want to add 50 to my bankacount to which i previously added 100 euros so my label that keeps track of the balance should give 150 but instead it gives me 50.
you are everytime creating a new object, rather than using the same object for a same person .
So if you have already created an object for persons AAA
and he is adding money , you need to use the same object created rather than creating it again .
this line i think is the problem :
Bankrekening BankrekeningL = new Bankrekening(bankrekeningLinks.Naam, 0);
Possible solution :
You might keep a list of your Bankrekening objects , and using LINQ check if for a person the object is already present .
If it is present then use the same object , else create a new object.
Something like
List<Bankrekening> list = new List<Bankrekening>();
if(list.Any(x=>x.Name == "XYZ")>
// your code to add
else
Bankrekening BankrekeningL2 = new Bankrekening(bankrekeningLinks.Naam, BankrekeningL.Saldo);
You need to move the declaration of BankrekeningL outside of the function into the form to preserve its value, currently you are creating a new instance every button click
Bankrekening BankrekeningL;
public FormName()
{
BankrekeningL = new Bankrekening("name");
}
private void StortL_Click(object sender, EventArgs e)
{
double saldodouble = 0;
int decimalL = Convert.ToInt32(tbDecimaleL.Text);
int wholeL = Convert.ToInt32(tbWholeL.Text) * 100;
int bedrag = wholeL + decimalL;
BankrekeningL.Stort(bedrag);
lbIsaldoL.Text = BankrekeningL.Saldo.ToString();
}

asp.net c# using session data to output more data

Ok guy,
i have made a simple program that has a web form where you fill in details fruit name, kg and cal count. i have then used session variables to get the fruit name from the form on default page and display them on about page in a drop down menu. that's all working fine, what i cant seem to work out is on the about page how to get it so the user selects a item from the drop down (created from form on default page) then enter a int how many they want (in text box) and have there selection and amount output on a list box on about page. il post the code i have so far any help would be much appreciated.
default page
public class Fruit
{
private string fName;
private int grams, calsPerGram;
private bool edible;
public Fruit(string n, int g, int c, bool e)
{
grams = g;
calsPerGram = c;
edible = e;
fName = n;
}
public int totalCalories()
{
return grams * calsPerGram;
}
public string getFruitInfo()
{
string s;
if (edible == true)
{
s = fName + " is yummy and it has " + totalCalories() +
"calories";
}
else
{
s = "Hands off! Not edible";
}
return s;
}
}
public partial class _Default : System.Web.UI.Page
{
List<Fruit> myBasket;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myBasket = new List<Fruit>();
Session["listSession"] = myBasket;// seassion start
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
// Session["Fruitname"] = TbxName.Text; // my session i have made
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
MyFruit.Add(TbxName.Text);
Session["Fruitname"] = MyFruit;
abc.Items.Clear();
Fruit f = new Fruit(TbxName.Text, int.Parse(TbxWeight.Text),
int.Parse(TbxCal.Text), CheckBox1.Checked);
myBasket = (List<Fruit>)Session["listSession"]; // session used
myBasket.Add(f);
foreach (var item in myBasket)
{
abc.Items.Add(item.getFruitInfo()); // List box used
}
}
public List<string> MyFruit { get; set; }
}
About page
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Drinklabel.Text = "Your Chosen Beverage is A " + DropDownList1.SelectedValue.ToString() + " Drink.";
}
public List<string> MyFruit { get; set; }
}
You do not necessarily need a separate class for calculating cost, but I recommend that you use a Label to display the selected fruit, amount desired and total price, like this in your About page:
Create a Button with Calculate text that has a click event handler, a calculatePrice method, a TextBox for quantity and a Label for display, like this:
protected void ButtonCalculate_Click(sender object, EventArgs e)
{
decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
TextBoxQuantity.Text.Trim());
LabelResult.Text = "You would like " + TextBoxQuantity.Text.Trim() +
DropDownList1.SelectedItem.Text + "(s) for a total of $" +
total.ToString();
}
private decimal calculatePrice(string fruitName, int quantity)
{
// Ask the database for the price of this particular piece of fruit by name
decimal costEach = GoToDatabaseAndGetPriceOfFruitByName(fruitName);
return costEach * quantity;
}

Categories