I have asked a similar question in the C# forum but seemed like a good idea to separate the issue and change forum. (Thanks Sam and Vulpes!)
If I want to access a control in another form from the current form or class, how do I do this?
How does it really work?
Form1.ListBox1 is clearly not enough.
Loading
VulpesPosted Apr 5, 2012, 12:02 PM
Another way to do it (apart from Application.OpenForms) is to define a static property in the form itself which exposes such a reference. This only works if there's only ever a single instance of a particular form which is usually the case:
From another form or class in the same application, you can then get your reference as follows:
Form1 f1 = Form1.Me;
There are (at least) 2 other ways (apart from using the Controls collection) to access a control on a form:
1. Change the control's Modifiers property from private to either internal or public so it can then be seen by other forms or classes in the application. You can then do:
ListBox lb = f1.listBox1;
2. Create an internal or public method (or a readonly property) on the form to expose the control to other forms or classes:
internal ListBox GetListBox()
{
return this.listBox1;
}
You can then do:
ListBox lb = f1.GetListBox();
Sam HobbsPosted Apr 14, 2012, 5:26 AM
Lars PerssonPosted Apr 14, 2012, 5:09 AM
Have you used LINQ. As I understand it you can save the objects to a relational database using LINQ.
Sam HobbsPosted Apr 14, 2012, 5:01 AM
As a learning exercise, a text file such as this can be educational. There is so much to learn and I understand that we need to prioritize what to learn.
Lars PerssonPosted Apr 14, 2012, 4:29 AM
A good explanation!
I think I said somewhere that I saved the objects or something but I only meant saving to a variabel. I was however saving to disc using streams in Java so it´s great that you showed me how.
Sam HobbsPosted Apr 14, 2012, 2:47 AM
Sam HobbsPosted Apr 14, 2012, 2:45 AM
As far as I know, you still have not specified how the data is saved. That however can affect how the data is processed by the program. I give you credit for asking specific questions. Many questions are quite general; asking how to write an entire program. My reply to many of them is that they need to ask specific questions. You are doing that so I need to give you credit for that. If I knew however how you are saving the data then that would help. The following is intended to show how to access data in anohter form. This is intended to be an object-oriented solution. This is not inended to be a complete program; it is primarily a sample of passing data to another form and getting data from the form.
In this sample, a CSV file of customers is read from and written to. That is done in the "Program" class which is in the Program.cs file. The Program class is static; it must be since it has the Main method which must be static. The class and the method must be static so that Windows can execute the program. So the Program clss in this sample has the following member:
Which is a list of Customer objects. I use a BindingList but a List would probably be the same for your purposes. The Customer class is:
{Of course your Customer class has more members but this is just a sample. The data is read (using GetCustomers()) before the main form is shown and then when the main form is closed the data is written (using PutCustomers()). So the Main has the following:
And the following are the GetCustomers() and PutCustomers():
{{{{}}}}{{{file.WriteLine(c.id + +c.name);}}}However note that the code shown above is incomplete; the tool I use to format source code is not perfect. So the following are two lines that are shown without the formatting tool that are the correct version of the code above.
char[] delimiters = { '\t', ' ' };
file.WriteLine(c.id +'\t'+c.name);
Okay so that is how the program reads and writes the data. The main form of the program has a DataGridView and a menu bar. The form has a BindingSource as a member; it is:
The Customers list is bound to the DataGridView in the form load event using:
That is all that is needed to bind the data to the control. You can download the attached project to see how it works.
Note that a DataGridView allows rows to be added and edited in it, so we do not need a second form. If however you do not want to use a DataGridView then this sample is useful for showing how to use a second form to edit the data; you do not have to use a DataGridView in your program. The main form also has a menu bar with commands to add or edit customers using a second form. The following code will use the second form to add a record:
DialogResult dr = f.ShowDialog();return ;Program .Customers.Add(c);Program .Customers.ResetBindings();In this sample, a row in the DataGridView needs to be selected for the edit to happen. The following will edit the selected row:
{return ;DialogResult dr = f.ShowDialog();return ;Program .Customers.ResetBindings();The important thing here is that the Form2 object is being created with a constructor that takes a Customer object as a parameter. That is the important thing and it is very fundamental to object-oriented programming and languages such as C#, Java and C++. There is nothing exotic or advanced about doing that. The Form2 class has a Customer object as a member; as in:
The Form2 class has a constructor that takes a Customer object as a parameter; the following is the complete constructor:
{this .c = c;The Constructor also sets the textboxes to the values of the Customer object. Then the Okay button click event does the following:
DialogResult = DialogResult .OK;The Cancel button click event does the following:
DialogResult = DialogResult .OK;The relevant portion of code is very simple. We simply pass an object to the constructor and the form uses just one object. The object (Customer) can have many more properties and regardless of how many properties it has, the constructor only needs one parameter.
Lars PerssonPosted Apr 7, 2012, 8:08 AM
I´ve making a simple system for a library.
You can create books as objects and customers as objects. Both of these are added to a List-controll.
You can then search for books, see what books there are and have a list of the customers.
It is an old project I made in Java that I´m trying to convert to C#.
Since there are a lot of information in the interface I want the list of customers to be a popup so it doesn´t take up space.
theLizardPosted Apr 6, 2012, 8:41 PM
a) create a public function in the form you want other forms to access its controls.
b) create a second constructor in the form you want to access another forms controls with 1 parameter, the form you want to access its controls.
namespace WindowsFormsApplication1
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
Form2 f = new Form2(this); //create the second form parsing this as its parameter.
f.Show();
}
//----------------------------------------------------------------------
//nothing out of the ordinary here, simply a way to return the form control to the calling form
public Control getControl(string name)
{
Control ctrl = null;
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i].Name == name)
{
ctrl = Controls[i];
break;
}
}
return (ctrl);
}
//----------------------------------------------------------------------
}
Then all you have to do in any other form that needs access to controls of other form is to call the getControl(...) method
eg ((TextBox)frm.getControl("TextBox1")).Text = "Hello World";
or TextBox te = (TextBox)frm.getControl("TextBox1"); //to access all the properties of TextBox1
eg te.Focus(), te.BackColor = Color.Blue;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
frmMain frm; //form scope
public Form2(frmMain f)
{
InitializeComponent();
frm = f; //assign f to frm;
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
((TextBox)frm.getControl("e2")).Text = "Hello World in TextBox of first form";
or it could be a combo box, list box, tree view
((ComboBox)frm.getControl("cbItems")).Items.Add("Hello World added to ComboBox on first form");
}
}
}
Sam HobbsPosted Apr 6, 2012, 7:39 PM
I will post a suggeston later today that you can consider for the future at least.
Lars PerssonPosted Apr 6, 2012, 7:12 PM
I´ve got it working now anyway.
What I´m doing is open Form2 using a button in Form1. I have a List controll containing objects that I want to show in a separate window to keep a cleaner interface.
Again, thanks to both!
Sam HobbsPosted Apr 6, 2012, 6:57 PM
As for having a reference to a form from another form, it depends on which form creates which form. It might also depend on whether a form is shown modally (with ShowDialog) or modelessly (using Show). So what is the relation of Form1 to the ohter form? Does Form1 create the other form or is it crated by the other form?
I prefer to use more object-oriented solutions but since that depends on what the objects are the answer depends on more information. We need clarification.
VulpesPosted Apr 6, 2012, 2:24 PM
So, if you wanted to access the listbox's DataSource property you could do so with:
object source = lb.DataSource;
However, you'd need to cast 'source' to its actual type (perhaps a DataTable or List
Lars PerssonPosted Apr 6, 2012, 12:52 PM
Some questions:
Can I set all the properties to public of a controll or do I have to choose Source for instance?
In the second example, can I then write lb.Source?