Creating multiple instances of class - c#

I have this code:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class Human
{
public string Name;
public Human(string name)
{
Name = name;
}
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Jane";
}
private void AddNewHuman_Click(object sender, EventArgs e)
{
Human h1 = new Human(textBox1.Text);
}
}
}
Is there a way, how to create a new instance of Human whenever I click the Button(AddNewHuman_Click)?
After clicking few times on the button, there will still be only one Human h1, right?

You will have to create list of object to store multiple object of human class.
I do changed here for you. I hope it will work for you.
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class Human
{
public string Name;
public Human(string name)
{
Name = name;
}
}
List<Human> objHumanList;
private void Form1_Load(object sender, EventArgs e)
{
objHumanList=new List<Human>();
textBox1.Text = "Jane";
}
private void AddNewHuman_Click(object sender, EventArgs e)
{
Human h1 = new Human(textBox1.Text);
objHumanList.add(h1);
/** Or
objHumanList.add (new Human(textBox1.Text))
**/
}
}
}

You can create a list of Humans and keep on adding a new Human to the list whenever the button is clicked.

Related

C# Passing data Between windows(WPF)

Recently picked up C# in university, trying to work out how to pass the variable "name" in MainWindow.xaml to ThirdWindow.xaml?
The below code is for the main window where the data is assigned to the variable "name"
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void NameBox_TextChanged(object sender, TextChangedEventArgs e)
{
string name = NameBox.Text;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondWindow newWin = new SecondWindow();
newWin.Show();
this.Close();
}
}
The below code is for the third window
public partial class ThirdWindow : Window
{
public ThirdWindow()
{
InitializeComponent();
}
public void LstThanks_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LstThanks.Items.Add(name);
}
}
You can simply pass that string name variable in the constructor as an argument to the ThirdWindow on Button_Click event.
private void Button_Click(object sender, RoutedEventArgs e)
{
var name = "your name";
var newWin = new ThirdWindow(name);
newWin.Show();
this.Close();
}
That string text will be available in the constructor of ThirdWindow.
public partial class ThirdWindow: Window
{
public ThirdWindow(string name)
{
InitializeComponent();
}
public void LstThanks_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LstThanks.Items.Add(name);
}
}
You can pass the variable through the constructor of the new window
var win = new ThirdWindow(name);
public ThirdWindow(string name)
{
InitializeComponent();
}
Another method is to pass it through an event message. This will require you to write a new message and add an event listener to your constructor in the ThirdWindow class. If you google this there are a variety of examples out there on how to do such a thing.
Here you are defining a local variable name. This variable is visible only inside the {} block. So we cannot use it anywhere else.
public void NameBox_TextChanged(object sender, TextChangedEventArgs e)
{
string name = NameBox.Text;
}
You could add a new string property into second window and pass value through that to all the way into third form.
So, add new property into your two windows (SecondWindow, ThirdWindow)
public string Name { get; set; }
These properties are holding the data for whole their lifetime (until they are closed).
Remove NameBox_TextChanged event handling, because we don't need it.
Add property setting inside your buttons click event
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondWindow newWin = new SecondWindow();
newWin.Name = NameBox.Text; //Store value into SecondWindow variable
newWin.Show();
this.Close();
}
Now when SecondWindow is visible (Show is called), you have name value available in Name variable and you should be able to copy this behavior for ThirdWindow.
If the ThirdWindow window is dependent on the name value then you can pass it through the constructor:
public partial class ThirdWindow : Window
{
public string Name { get; set; }
public ThirdWindow(string name)
{
InitializeComponent();
Name = name;
}
}
or if not then make a method on the ThridWindow to set the name:
public partial class ThirdWindow : Window
{
public string Name { get; set; }
public void SetName(string name)
{
Name = name;
}
}

avoid initializing list with data

So, I have two forms. The form1 has a button to open the form2. In the form2 I have a list of elements that I fill with elements I create in the form2. My problem is, when I close my form2 and reopen it, my list is empty. I know that is because Im initializing my list again (ListaComida = new List<Comida>();), so I get my data erased but I dont see how to solve this.
My code
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addDia_Click(object sender, EventArgs e)
{
string dia = (DateTime.Today.ToString("dd/MM/yyyy"));
TabPage myTabPage = new TabPage(dia);
tabControl1.TabPages.Add(myTabPage);
}
private void AddComida_Click(object sender, EventArgs e)
{
FormAddComida addComida = new FormAddComida();
DialogResult resultaod = addComida.ShowDialog();
}
}
Form2
public partial class FormAddComida : Form
{
public List<Comida> ListaComida;
public FormAddComida()
{
InitializeComponent();
ListaComida = new List<Comida>();
}
private void addComidaAdicionar_Click(object sender, EventArgs e)
{
Comida comidaAdicionada = new Comida(tbNome.Text,
Convert.ToInt32(tbCalorias.Text),
Convert.ToInt32(tbHidratos.Text),
Convert.ToInt32(tbProteinas.Text),
Convert.ToInt32(tbGorduras.Text)
);
ListaComida.Add(comidaAdicionada);
RefreshListaComida();
}
private void RefreshListaComida()
{
lbListaComida.Items.Clear();
lbListaComida.Items.AddRange(ListaComida.ToArray());
}
private void AddComidaCancelar_Click(object sender, EventArgs e)
{
this.Close();
}
}
You can use MemoryCache, even if you close your form your List will stay in Memory and you can retrieve by the Key. But if you need to save this data permanently (or long time running the app )i recommend you store in a DB.
using System.Runtime.Caching;
private ObjectCache cache = MemoryCache.Default;
public class Food
{
public string Name { get; set; }
public double Price { get; set; }
}
public void AddFood()
{
FoodList.Add(new Food { Name = "Pizza", Price = 10 });
FoodList.Add(new Food { Name = "Fries", Price = 5 });
cache.Add("UserCacheFood", FoodList, DateTimeOffset.MaxValue);
}
public List<Food> ReturnListFromCache()
{
return (List<Food>)cache.Get("UserCacheFood");
}
private void button1_Click(object sender, EventArgs e)
{
AddFood();
var result = ReturnListFromCache();
}
private void button2_Click(object sender, EventArgs e)
{
var ret2 = ReturnListFromCache();
}

How to access public static class from a windows form

I hope that my question is relevant to be answered because I'm a newbie.
For example, I have two coding named with Class1.cs and Form1.cs. Basically, Class1.cs is the program where the process of image filtering is occured, meanwhile in Form1 is the program where I allow it to load an image from a file.
Is it possible for me to access Class1 from Form1 right after I click on the button to process it?
Class1.cs
public class Class1
{
public static class Class1Program
{
// My program for image filtering is starting here
}
}
Form1.cs
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
private void LoadImageButton_Click(object sender, EventArgs e)
{
// My program here is to open up a file image right after I click on this button
}
private void ResultButton_Click(object sender, EventArgs e)
{
// Here is the part where I don't know how to access the program from "Class1.cs".
// I'm expecting the image that I've load before will be able to filter right after I clicked on this button
}
}
I'm wondering if there is a need to add or edit some program on the "Program.cs".
I'm hoping that my question can be answered. Thank you so much for your time.
Let me add one property and a method to the static class for make it understandable. Let the Class1Program looks like the following:
public static class Class1Program
{
public static int MyProperty{get; set;} // is a static Property
public static void DoSomething() // is a static method for performing the action
{
//my program for image filtering is starting at here
}
}
Now you can access the method and property inside the Form1 like this:
private void ResultButton_Click(object sender, EventArgs e)
{
Class1.Class1Program.MyProperty = 20; // assign 20 to MyProperty
int myint = Class1.Class1Program.MyProperty; // access value from MyProperty
Class1.Class1Program.DoSomething();// calling the method to perform the action
}
You can do one of these two things:
1.You can access data in Class1 by using static variables:
namespace MyProgram
{
class Class1
{
public static int Class1Variable;
}
}
namespace MyProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void LoadImageButton_Click(object sender, EventArgs e)
{
//Load image logic
}
private void ResultButton_Click(object sender, EventArgs e)
{
Class1.Class1Variable = 1;
}
}
}
2.You can create an instance of Class1 inside Form1:
namespace MyProgram
{
class Class1
{
public int Class1Variable;
public Class1()
{
}
}
}
namespace MyProgram
{
public partial class Form1 : Form
{
public Class1 c1;
public Form1()
{
InitializeComponent();
c1 = new Class1();
}
private void LoadImageButton_Click(object sender, EventArgs e)
{
//Load image logic
}
private void ResultButton_Click(object sender, EventArgs e)
{
c1.Class1Variable = 1;
}
}
}

Can't transfer tbox from 1 form to another tbox in another form c#

I have 2 forms, Form1 is the parent and ALog is the child. My goal is to have a textbox's text from Form1 (form1textbox) contents transfer over to a textbox on ALog (alogcheckbox)
This has to be done on the formload event on Alog and when the form shows from a button click on Form1
This is what I have currently:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string LabelText
{
get { return form1textbox.Text; }
set { form1textbox.Text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
ALog alogform = new ALog();
alogform.Show();
}
}
ALog:
public partial class ALog : Form
{
public ALog()
{
InitializeComponent();
}
public Form Alog;
private void button1_Click(object sender, EventArgs e)
{
}
private void ALog_Load(object sender, EventArgs e)
{
this.Form1.LabelText = textBox1.Text;
}
}
I've seen other questions similar to mine and answers as well, but I can't seem to manage to get this to work.
Any help is appreciated, thanks.
You want to add a constructor to ALog that takes the value, and initialize it that way.
ALog becomes:
public partial class ALog : Form
{
public ALog(string value)
{
InitializeComponent();
this.alogcheckbox.Text = value;
}
public Form Alog;
private void button1_Click(object sender, EventArgs e)
{
}
}
And from Form1:
private void button1_Click(object sender, EventArgs e)
{
ALog alogform = new ALog(form1textbox.Text);
alogform.Show();
}

C# Send parent form data to child form

Trying to get this active in another form. I want the objects from listBox1 to go to the labels: label3 and label4 in form2. PropertyA should assign to label3 and PropertyB to label4. It will simply load the data from form1. The question is in the form2 code. When an item is selected form the listbox it will write the properties for prepare them for the next form2 instance.
Most of this is fairly short and simple code...
Made a simple program to illustrate...
FOUND THE SOLUTION.... SEE FORM2, it was a problem of casting between forms the listbox1.SelectedItems as object of SpecialClass type.
Class
namespace WindowsFormsApplication1
{
class SpecialClass
{
public string PropertyA { get; set; }
public double PropertyB { get; set; }
#region [Methods]
public override string ToString()
{
return string.Format("PropertyA: {0}, PropertyB: {1}", this.PropertyA, this.PropertyB);
}
#endregion
}
}
Form1
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void AddBtn_Click(object sender, EventArgs e)
{
SpecialClass o = new SpecialClass();
o.PropertyA = textBox1.Text;
o.PropertyB = double.Parse(textBox2.Text);
listBox1.Items.Add(o);
}
#region [Currently unused methods]
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
#endregion
private void openNewForm(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show(this);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SpecialClass o = ((ListBox)sender).SelectedItem as SpecialClass;
label3.Text = o.PropertyA.ToString();
label4.Text = o.PropertyB.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Form2
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
Form1 form1Data = new Form1();
public Form2(Form1 _form1)
{
InitializeComponent();
form1Data = _form1;
}
private void label3_Click(object sender, EventArgs e)
{
SpecialClass oF2 = form1Data.listBox1.SelectedItem as SpecialClass;
label3.Text = oF2.PropertyA.ToString();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}

Categories