firstly this is my first post here so sorry for bad format and yada yada yada. Now, I'm trying to learn C# for my uni classes and I have a problem with some basic windows forms and c# logic so if you could help me out I would really appreciate it!
So, I created my form and it has 2 text boxes and a button. Uppon pressing the button, I want the program to create a new class member for a list. (think i got the explanation a bit wrong in the end so I'll link my code here). So basically here we go:
Main program :
namespace AddPersonTest
{
public static class Program
{
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
List<Person> Persoane = new List<Person>();
}
}
}
Persons class:
namespace AddPersonTest
{
public class Person
{
public int cod;
public int sex;
Person (int nCod, int nSex)
{
cod = nCod;
sex = nSex;
}
}
}
Button and textboxes code:
namespace AddPersonTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void lblCod_Click(object sender, EventArgs e)
{
}
public void btnAdd_Click(object sender, EventArgs e)
{
Persoane.Add(txtCod, txtSex);
}
private void txtSex_TextChanged(object sender, EventArgs e)
{
}
private void txtCod_TextChanged(object sender, EventArgs e)
{
}
}
}
In case you wanted to have the persons added on click to be static throughout your application, you could do like the below. You have created the list inside the main method which is not the right place to maintain your application state. Use the below class and on buttonclick, just call PersonStore.AddPerson(....);
public static class PersonStore {
private static List<Person> persons = new List<Person>();
public static void AddPerson(Person p) {
persons.Add(p);
}
public static List<Person> GetAllPersons() {
return persons;
}
}
In case you wanted to have these handled with services you could just do that with the help of service classes and Data Access layer classes which can be written if your requirement is to store in DB.
Related
i'm making a program where it will count each answer correct on each window and display the counter as a result. I've already figured out how to count the answer and display it on one page.
If anyone could point me in a direction on how to keep that count throughout multiple pages until the last one? Not asking for people to write me code out just don't have a lot of knowledge of carrying data through multiple windows.
Any help/links are appreciated.
Thanks.
EDIT: I took your advice and assigned it to a static variable, this code updates the lblScore to 1, but when it navigates to the last page, it doesn't show that value in the label. Any advice?
public partial class Question1 : Window
{
public Question1()
{
InitializeComponent();
}
private void Question1_Load(object sender, EventArgs e)
{
lblScore.Content = MyGlobals.Score.ToString();
}
private void btnNext1_Click(object sender, RoutedEventArgs e)
{
if (textBox.Text == "1111")
{
MyGlobals.Score = MyGlobals.Score + 1;
lblScore.Content = MyGlobals.Score.ToString();
MessageBox.Show("Noice");
}
new Question3().Show();
this.Hide();
}
}
}
public static class MyGlobals
{
public static int Score;
}
/*Question3 Window*/
namespace Maths_Quiz
{
/// <summary>
/// Interaction logic for Question3.xaml
/// </summary>
public partial class Question3 : Window
{
public Question3()
{
InitializeComponent();
}
private void Question3_Load(object sender, EventArgs e)
{
lblScore.Content = MyGlobals.Score.ToString();
}
private void btnReturn_Click(object sender, RoutedEventArgs e)
{
new MainWindow().Show();
this.Hide();
}
}
}
Create an overload for the constructor and pass in the data as a parameter or store the data in properties settings
So i have form1 which has backgroundworker (dragged and dropped via design view).
I can get it to work in the places i need, however I need to call it from a public method.
In this public method
Utility.initpacks(object sender, EventArgs e,string formname)
SO my DoWork is in Form1.
I the public utility within the form do do a bunch of things, then THAT function needs to use the background worker inside Form1 again!
I could just copy the public method and put in the place of the method reference and all is well.. but that defeats the purpose of a public method doesn't it!?
Any ideas would be great thanks :)
EDIT:
SO my current setup (without a bunch of stuff not important):
public partial class frmimportinstitutions : Form
{
private void btnNext_Click(object sender, EventArgs e)
{
Utility.initpacks(sender, e, this.FindForm().Name);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Do stuff
}
}
public static class Utility
{
public static void initpacks(object sender, EventArgs e,string formname)
{
//I WANT TO USE THE BACKGROUND WORKER HERE
//Do a public method
//I want to stop the background worker here
}
}
Update (basd on comments):
Michael comments just mentioned to put the background worker starting in a public method:
public void startplash(string starttext)
{
if (!backgroundWorker1.IsBusy)
{
splashtext = starttext;
backgroundWorker1.RunWorkerAsync();
}
}
Now i want to call this method from the other method. In order to do this, the other method (init packs) needs to know where this method is doesnt it.
EG.
form1.startsplash("hello world")
So now i just need to send Form1 info to init packs...
Would this be ok:
Initpacks(Form Owner)
{
Owner.startsplash("hello world")
}
Another update!
Thanks for Michael we so far have this:
public static class Utility
{
public static void RunWorkerOfForm1()
{
var target = (Form1)Application.OpenForms.OfType<Form1>().FirstOrDefault();
target?.RunWorker();
}
}
Now I need to get this to work with different forms.. I havent tried the below but this is what i am going to try next.. correct me if i am wrong:
public static class Utility
{
public static void RunWorkerOfForm1(Form owner)
{
var target = (owner)Application.OpenForms.OfType<owner>().FirstOrDefault();
target?.RunWorker();
}
}
Final Answer (as per the ticked answer) - but using my code:
public partial class frmholidaypacks : Form, IWorker
{
private void btnextrapacks_Click(object sender, EventArgs e)
{
Utility.futurepacks<frmholidaypacks>(sender, e, pxid);
}
}
public interface IWorker
{
void startplash(string starttext);
}
public void startplash(string starttext)
{
if (!backgroundWorker1.IsBusy)
{
splashtext = starttext;
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Doing work. Using Splashtext string.
}
public static void futurepacks<T>(object sender, EventArgs e, int pxid) where T : IWorker
{
var target = (T)Application.OpenForms.OfType<T>().FirstOrDefault();
target?.startplash("Creating future packs");
}
100% Credit goes to Michael for working on this with me!
EDITED!
Ok, now I got it. Every form you want to run have to implement the IWorker interface. Then you pass the concrete Form to use as a generic parameter to the RunWorker function. The where clause only allows implementations of the IWorker interface - its (currently) not restricted to Form-instances.
public partial class Form2 : Form, IWorker
{
public Form2()
{
InitializeComponent();
}
public void RunWorker()
{
if (backgroundWorker1.IsBusy) return;
backgroundWorker1.RunWorkerAsync();
}
private void button1_Click(object sender, EventArgs e)
{
UtilityX.RunWorker<Form2>();
}
}
public static class UtilityX
{
public static void RunWorker<T>() where T : IWorker
{
var target = (T)Application.OpenForms.OfType<T>().FirstOrDefault();
target?.RunWorker();
}
}
public interface IWorker
{
void RunWorker();
}
Have you tried to use a static method,
you can put your code in a static method if you want too use it from multiple places.
public class MyClass
{
public static void MyMethod()
{
//..
}
}
hi guys im trying to create a button which can take my information from one textbox to another but i the informationer is in Contactformula.xaml and i need it over to Mainwindow.xaml hope u understand what i mean here is the code...
Mainwindow.xaml.cs
namespace debug
{
public partial class MainWindow : Window
{
public ContactFormula CF = new ContactFormula();
public object Frame { get; private set; }
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ContactFormula win2 = new ContactFormula();
win2.Show();
}
ContactFormula.xaml.cs
namespace debug
{
/// <summary>
/// Interaction logic for ContactFormula.xaml
/// </summary>
public partial class ContactFormula : Window
{
public ContactFormula()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
}
and here is a screenshot of the program so maybe u understand me better
Try making the list of contacts a static property in a static class, that way you can get or add contacts from anywhere in the program.
public static class Session
{
public static List<Contact> Contacts = new List<Contact>();
}
you can add contacts from any page using:
Session.Contacts.Add(contact);
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;
}
}
}
Still in the process of learning C#, but I'm a bit confused on something here.
For example, I have a textbox on my form and it has the name of testTXT. Based on the code below, I've created a new class outside of the public partial one that's there by default, and now I'm trying to access testTXT but I cannot. I'm going to also need to access several other textboxes and things later on as well.
Here's a snippet of the code I'm working with thus far:
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass();
gc.CreatePackage("C:\\Users\\user\\Downloads\\output.docx");
}
private void browseButton_Click(object sender, EventArgs e)
{
var fsd = new FolderSelect.FolderSelectDialog();
fsd.Title = "Select folder to save document";
fsd.InitialDirectory = #"c:\";
if (fsd.ShowDialog(IntPtr.Zero))
{
testTXT.Text = fsd.FileName;
}
}
}
public class GeneratedClass
{
**trying to access testTXT right here, but can't.**
}
}
Any help would be greatly appreciated.
You could do this (see other answers), but you really shouldn't.
Nobody but the containing form has to know about the textboxes in it. Who knows, they might disappear, have their name changed, etc. And your GeneratedClass could become a utility class used by lots of forms.
The appropriate way of doing this, is to pass whatever you need from your textbox to your class, like so:
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass();
gc.CreatePackage(this.testTxt.Text);
}
public class GeneratedClass
{
public void CreatePackage(string name) { // DoStuff! }
}
This is because you have your TextBox type defined in Form1 class as private member. Thus can't be access with another class instance
Your question has little to do with C#, more to do with Object Oriented Concepts.
Instance of TextBox has to be given to 'GeneratedClass' somehow.
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass(testTXT);
gc.DoSomething();
gc.CreatePackage("C:\\Users\\user\\Downloads\\output.docx");
}
private void browseButton_Click(object sender, EventArgs e)
{
var fsd = new FolderSelect.FolderSelectDialog();
fsd.Title = "Select folder to save document";
fsd.InitialDirectory = #"c:\";
if (fsd.ShowDialog(IntPtr.Zero))
{
testTXT.Text = fsd.FileName;
}
}
}
public class GeneratedClass
{
TextBox _txt;
public GeneratedClass(TextBox txt)
{
_txt= txt;
}
public void DoSomething()
{
txt.Text = "Changed the text";
}
}
}
You must make testTXT public.
See Protection level (Modifiers) of controls change automaticlly in .Net.
And access to TextBox as
public class GeneratedClass
{
GeneratedClass(Form1 form)
{
form.testTXT.Text = "1";
}
}