I have 3 forms: form1(which I want to use my List from form3 in which I create List and Add things to it), form2 ( which contains a button to go back to form1 and a button to go to form3 and get values to the list.
I tried creating the following class:
public class ListArticle
{
public List<string> Clothes { get; private set; }
public List<string> Colors { get; private set; }
public ListArticle()
{
Clothes = new List<string>();
Colors = new List<string>();
}
}
and then declare trying Adding things in the List from form3 like this:
// This is the Declaration
public ListArticle _articles = new ListArticle();
public ListArticle Articles
{
get
{
return _articles;
}
set
{
_articles = value;
}
}
This is how I add:
_articles.Clothes.Add("T-shirt " + tshirt_number.ToString());
_articles.Colors.Add(closestColor2(clist, color));
and this is how I am trying to get the values:
when I close form3
I do this:
Form2 frm = new Form2();
frm.Show();
Articles = _articles;
this.Hide();
in form2 I do nothing..
and in form1 I tried to do it like this:
//declaration
public ListArticle Articles;
public ListArticle _articles
{
get
{
return Articles;
}
set
{
Articles = value;
}
}
//and this is how I tried to do it but it returns null everytime.
private void button3_Click(object sender, EventArgs e)
{
try
{
Form3 f = new Form3();
f.Articles = Articles;
foreach (string c in Articles.Clothes)
{
MessageBox.Show(c);
}
}
catch
{
MessageBox.Show("Articles is null.");
}
}
If you want to be able to share the articles between all forms you could make the Clothes and Colors collection static:
public class ListArticle
{
public static List<string> Clothes { get; private set; }
public static List<string> Colors { get; private set; }
static ListArticle()
{
Clothes = new List<string>();
Colors = new List<string>();
}
}
You can then add articles form one form like this:
ListArticle.Clothes.Add("T-shirt " + tshirt_number.ToString());
ListArticle.Colors.Add(closestColor2(clist, color));
...and retrieve articles from another form like this:
private void button3_Click(object sender, EventArgs e)
{
try
{
foreach (string c in ListArticle.Clothes)
{
MessageBox.Show(c);
}
}
catch
{
MessageBox.Show("Articles is null.");
}
}
Using this approach you don't have to create any additional "article" properties in either of the forms. You just access the same static collections from all forms.
Related
As you can see I instantiated the classes I need into the form_load, in order to use methods and classes features. The problem is that I need to Call the item NuovoCliente from CreateClientemethod, but I don't know how to do, since intellisense, even when I try to type, does not show any link to NuovoCliente.
The class you can see with the method is ClienteModel.
Which is basically structured like this:
public class ClienteModel
{
public int IDCliente { get; set; }
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
}
This is my method, which is placed in DBMemoryManager class:
public class DBMemoryManager : DBManager
{
//Array
ClienteModel[] MemoryClienti = new ClienteModel[0];
public int CreateCliente(ClienteModel model)
{
ClienteModel NuovoCliente = new ClienteModel();
int MaxCID = MemoryClienti.Select(ClienteModel => ClienteModel.IDCliente).Max();
MemoryClienti[0] = NuovoCliente;
NuovoCliente.IDCliente = MaxCID++;
return NuovoCliente.IDCliente;
}
This is how my Form start:
public partial class Form1 : Form
{
DBMemoryManager dbMemoryManager = null;
ClienteModel clienteModel = null;
OrdineModel ordineModel = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dbMemoryManager = new DBMemoryManager();
clienteModel = new ClienteModel();
ordineModel = new OrdineModel();
}
Return a ClienteModel from this method.
public ClienteModel CreateCliente(ClienteModel model)
{
ClienteModel NuovoCliente = new ClienteModel();
int MaxCID = MemoryClienti.Select(ClienteModel => ClienteModel.IDCliente).Max();
MemoryClienti[0] = NuovoCliente;
NuovoCliente.IDCliente = MaxCID++;
return NuovoCliente;
}
Now access data from Form_load
public partial class Form1 : Form
{
ClienteModel clienteModel = null;
OrdineModel ordineModel = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
clienteModel = new ClienteModel();
ordineModel = new OrdineModel();
DBMemoryManager dbMemoryManager = new DBMemoryManager(); //initialize here
ClienteModel nuovoCliente = dbMemoryManager.CreateCliente(clienteModel)
//here you can get all data from nuovoCliente
}
here is the data.
I was trying to create a personal list using WinForms. I try to create a new entry via button click. I have a list of objects with string properties Name and Number.
How can I show the list of objects in my ListBox?
namespace sometestname
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Personallistshow(object sender, EventArgs e)
{
}
public void NewItemButton_Click(object sender, EventArgs e)
{
Personallist.Add(new Entrys() { Name = NameBox.Text, Number = Numbox.Text });
}
public List<Entrys> Personallist= new List<Entrys>();
}
public partial class Entrys
{
public string Name { get; set; }
public string Number { get; set; }
}
}
The user has 2 Textboxfields. If they click the NewItemButton, than create a new Entrys object. This new Entrys object should be added to Personallist object and ListBox should show the updated list.
List<Entrys> someList = ...;
Personallist.DataSource = someList;
You should use a bindinglist and set the datasourcebinding after initializing your form.
Something like:
public partial class Form1 : Form
{
public BindingList<Entrys> Personallist = new BindingList<Entrys>();
public Form1()
{
InitializeComponent();
comboBox1.DataSource = Personallist;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Number";
}
private void button1_Click(object sender, EventArgs e)
{
Personallist.Add(new Entrys() { Name = "TESTNAME", Number = "TESTNR" });
}
}
public partial class Entrys
{
public string Name { get; set; }
public string Number { get; set; }
}
I'm still fairly new to programming, and have started a project where I'm trying to seperate functionality of the program into classes, where each class handles most everything related to that specific part of the program.
I have one class, called DirectoryMonitors, that creates an object that monitors a directory with FileSystemWatcher. I'm trying to add items to a ListBox on the MainForm from an instance of this DirectoryMonitors class. However, it seems I'm unable to call the method in MainForm unless it's static - but if it's static, I can't access my ListBox.
Relevant part of my DirectoryMonitor class:
public class DirectoryMonitorData
{
public bool WatcherActive { get; set; } = true;
public string EQVersion { get; set; }
public string FolderLocation { get; set; }
}
public class DirectoryMonitor : DirectoryMonitorData
{
private void FolderWatcher_Changed(object sender, FileSystemEventArgs e)
{
FileInfo fi = new FileInfo(e.FullPath);
if (!IsFileLocked(fi))
{
int startPos = e.FullPath.LastIndexOf("\\") + 1;
int endPos = e.FullPath.IndexOf("-Inventory") - startPos;
string character = e.FullPath.Substring(startPos, endPos);
MessageBox.Show(character);
string[] delimiters = { ControlChars.Tab.ToString() };
using (TextFieldParser parser = Microsoft.VisualBasic.FileIO.FileSystem.OpenTextFieldParser(e.FullPath, delimiters))
{
// Process the file's lines.
while (!parser.EndOfData)
{
try
{
string[] fields = parser.ReadFields();
MainForm.addLogToListBox(fields[0]);
for (int i = 1; i <= 5; i++)
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
private bool IsFileLocked(FileInfo file)
{
...
}
}
Relevant part of my MainForm class:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
public void addLogToListBox(string logMessage)
{
logsListBox.Items.Insert(0, logMessage);
}
}
UPDATED CODE:
public FileSystemWatcher FolderWatcher = new FileSystemWatcher();
public DirectoryMonitor()
{
FolderWatcher.NotifyFilter = NotifyFilters.LastWrite;
FolderWatcher.Filter = "*-Inventory.txt";
FolderWatcher.Changed += FolderWatcher_Changed;
}
public void setupDirectoryMonitorList()
{
foreach (DirectoryMonitorData dmd in MainForm.directoryMonitorList)
{
DirectoryMonitor dm = new DirectoryMonitor()
{
WatcherActive = dmd.WatcherActive,
FolderLocation = dmd.FolderLocation,
EQVersion = dmd.EQVersion
};
if (dm.WatcherActive)
{
dm.FolderWatcher.Path = dm.FolderLocation;
dm.FolderWatcher.EnableRaisingEvents = true;
dm.FolderWatcher.NotifyFilter = NotifyFilters.LastWrite;
dm.FolderWatcher.Filter = "*-Inventory.txt";
dm.FolderWatcher.Changed += FolderWatcher_Changed;
}
MainForm.directoryMonitorObjects.Add(dm);
}
}
Add a property to your DirectoryMonitorData class and pass list box to it:
public class DirectoryMonitorData
{
public bool WatcherActive { get; set; } = true;
public string EQVersion { get; set; }
public string FolderLocation { get; set; }
public ListBox Logs {get; set;}
}
and then:
DirectoryMonitor monitor = new DirectoryMonitor { Logs = logsListBox };
now in your class you can simply add anything to that listbox:
Logs.Items.Add(Something);
The way I normally do that is to add a constructor to the class, that takes a 'MainForm' parameter, then save the 'MainForm' parameter in a field.
public class DirectoryMonitor : DirectoryMonitorData
{
public DirectoryMonitor(MainForm form)
{
this.mainForm = form;
}
private MainForm mainForm;
}
Now you can access all public methods an properties of MainForm by using the field mainForm.
Alternative:
Create an eventhandler in your class (with a custom EventArgs). Then from your 'MainForm', subscribe to that event. Now the class does not have to know anything about the form. You just need to Invoke the eventhandler in your class.
I have a Data class where I store certain values like State, Initials, etc.
I have a get/set for these values.
It's a windows form app, so I made another view sort of like this
public partial class Actions : Form
{
public Actions()
{
InitializeComponent();
}
private void Actions_Load(object sender, EventArgs e)
{
testLabel.Text = ;
}
}
So just as a test case I want to set this labels .Text value to my string from Data which is just like
class Data
{
public string State { get; set; }
public string Initials { get; set; }
public Data()
{
}
}
Data is being set like this from the home class
Data dat = new Data();
dat.State = "IN";
I saw that online the best way to do this is pass it as a value, but I'm not sure of the best way to go about this.
If you need State available on form load event, then best way is passing state value (or your Data object if you need more than just state string) to form's constructor:
public Actions(string state) // or public Actions(Data data)
{
InitializeComponent();
State = state;
}
Then
private void Actions_Load(object sender, EventArgs e)
{
testLabel.Text = State;
}
Is this what you are trying to do?
public partial class Actions : Form
{
private Data myData;
public Actions()
{
myData = new Data();
myData.State = "California";
//the best state :D\\
InitializeComponent();
}
private void Actions_Load(object sender, EventArgs e)
{
testLabel.Text = myData.State;
}
}
EDIT
public partial class Actions : Form
{
private Data myData;
public Actions(Data otherDataObject)
{
myData = otherDataObject;
testLabel.Text = myData.State; //here
InitializeComponent();
}
private void Actions_Load(object sender, EventArgs e)
{
testLabel.Text = myData.State; //or here
}
}
When loading the form, pass your data object to the form and it will be available anywhere within this form
You could add a Data property to the form.
public class Data
{
public string State { get; set; }
}
public partial class Actions : Form
{
public Data Data { get; set; }
private void Actions_Load(object sender, EventArgs e)
{
testLabel.Text = data.State;
}
}
Elsewhere, if you already have a Data object dat
var actionForm = new Actions();
actionForm.Data = dat;
Okay, I've figured it out.
I was doing the right thing initially, but I needed to make my Data class public.
My Code is:
public partial class Actions : Form
{
public Actions(Data data)
{
InitializeComponent();
testLabel.Text = data.State;
}
}
public class Data
{
public string State { get; set; }
public string Initials { get; set; }
I have some label that should display actual amount of items that contain BindingList that bound to the DataGridView.
I tried to bind in this way:
CountOfLoadedItemsLabel.DataBindings.Add("Text", _items.Count, String.Empty);
But when BindingList updates, the label that bound to its Count property not changes.
Never used BindingList<T> but this worked for me:
public partial class Form1 : Form
{
private BindingList<Test> list;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.list = new BindingList<Test>
{
new Test(1,"Entry"),
new Test(2,"Another Entry")
};
dataGridView1.DataSource = new BindingSource(list,null);
list.ListChanged += list_ListChanged;
list.Add(new Test(3, "After Binding"));
}
void list_ListChanged(object sender, ListChangedEventArgs e)
{
CountOfLoadedItemsLabel.Text = string.Format("Items: {0}", list.Count);
}
}
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public Test(int id, string name)
{
this.Id = id;
this.Name = name;
}
}