C# Get field from Main Form - c#

I have a main form and I need in other class get or set field from Main Form. I created public property in Main Form:
public partial class MainForm : Form
{
public string get_txt()
{
return phone.Text; //phone - textbox
}
}
But in other class I can't get this property:
MessageBox.Show(MainForm.get_txt); //there error. It doesn't seemed get_txt property.
I'm sorry for this simpliest question, but I really don't know this. Everywhere wrote that simpliest way to do it - in class of Main Form create public property for needed private field in Main Form. What do I wrong?

So the MessageBox.Show(MainForm.get_txt) won't compile as you're trying to refer to a static property, not an instance method.
I'm not a winforms dev, so this is a bit of a guess:
Somewhere in your code you will have a call like var main = new MainForm(). On that instance i.e. main you will be able to call main.get_txt().
As a side note, given that you're working in C# it'd be good to name the method to something a little more idiomatic, perhaps public string GetPhoneNumber() or better yet make it a property:
public string PhoneNumber
{
get { return phone.Text; }
}

Make instance of MainForm and than call it.
Mainform _mainform=new Mainform();
MessageBox.Show(_mainform.Get_text);

Your MainForm is not static class, you can not use like that. If u want access the MainForm(methods or variables), you have to assing the variable.
MainForm mForm = new MainForm();
MessageBox.Show(mForm.getText());

Thanks to you all.
but when I create a new istance of Main Form all controls in it will be initializing like in my current Main Form?

Related

How can i pass a list from my first form to a second form, add data to it and then show it on my first form? C#

From what i've read so far i've done this:
On my first form:
public partial class FPrincipal : Form
{
List<Grua> ListaGruas = new List<Grua>();
List<Semirremolques> ListaSemirremolques = new List<Semirremolques>();
List<Clientes> ListaClientes = new List<Clientes>();
// this is the menu strip i click to create my new form,
// send my list and add my values
private void miEquipoCargar_Click(object sender, EventArgs e)
{
EquiposCargar FormEquiposCargar = new EquiposCargar(ListaGruas);
FormEquiposCargar.ShowDialog();
}
}
And on my second form:
public partial class EquiposCargar : Form
{
// I saw some videos on youtube and this is how the pass some values,
// but it doesnt work with lists
public EquiposCargar(List<Grua>listaGrua)
{
InitializeComponent();
}
}
Could anyone please help me? im stuck.
The error says the parameter List<Grua>listaGrua is less accesible than the method EquiposCargar.EquiposCargar(List<Grua>)
just another question! how do i use the list on my second form? lol...
because it says the name listaGrua is not defined in the actual
content. It looks like i have to create a new variable and assign the
list parameter than i sent, right? but im doing it and its still not
working
That's correct, you need to create a variable in your second form to hold that reference. In the constructor, simply assign the passed in reference to your form's reference:
public partial class EquiposCargar : Form
{
private List<Grua> listaGrua;
public EquiposCargar(List<Grua> listaGrua)
{
InitializeComponent();
this.listaGrua = listaGrua;
}
}
Note the use of the this keyword. Now you should be able to use listaGrua from anywhere in your second form.

Passing tabConrol properties from on form to another

I am using two forms in a windows form application in C#.I want to pass the tabControl's properties like its "Tabpage count" from first form to second form. Can anyone help me here?I can't create object of first form in second form and call a function beacuse for a new forn object, the tabcontrol gets refreshed.
Inside your first form create an instance of your second Form class as this
Form frm= the instance of your secand form
after that show the instance of your secand form, now you exactly have an instance of your secand form inside your first form and can use all the public properties of it
You can create static public functions exposing desired control properties like in below code.
public static Color TabColor()
{
return Form1.Fom1TabControl1.SelectedTab.ForeColor;
}
and you can access Form1 properties like below;
private void Form2_Load(object sender, EventArgs e)
{
this.Fom2TabControl1.SelectedTab.ForeColor = Form1.ForeColor;
}
First Check your class accessibility and set to public if not work set public static, maybe your namespaces is different
hope it helps
This can be achieved in two ways
Aprroach 1:
Create a public variable in Form2
public int intTabCount=0;
and in Form1, you should call Form2 like
Form2 objForm2 = new Form2();
objForm2.intTabCount = tabPageCountVariable;
objForm2.Show()
Aprroach 2:
Create a parameterized constructor and public variable in Form2
public int intTabCount=0;
public Form2(int TabCounts)
{
intTabCount = TabCounts; // and use intTabCount for your class
}
and call from Form1 like
Form2 objForm2 = new Form2(tabPageCountVariable);
objForm2.Show();
Now if you want to pass value through any events like clicking an button in Form1 which updates anything in Form2, use the below link
Passing Values Between Windows Forms c#

Fill a list of objects from another class

I know this is a basic question, but I am struggling with it for quite some time now..
I have a main form in which I have a List<Filenames> and I have another class that gets invoked by the main form. This class has to insert some entries in my List<Filenames>.
In main form, I have the list initialized as:
public List<Filenames> filenamesList = new List<Filenames>();
And in the other class I do:
MainForm mainForm = new MainForm();
mainForm.filenamesList.Clear();
//then I have a for loop in which I perform some changes
mainForm.filenamesList.Add(new Filenames { name = "filename1", id = 1 } );
//it works until here and a new Filenames is added to the list
//then we go back to the main form
The problem is that now the List<Filenames> is empty. What am I doing wrong?
I have another class that gets invoked by the main form
I suspect the problem is here:
MainForm mainForm = new MainForm();
This creates a new MainForm instance, which is not the same instance as the MainForm that invokes the function.
I would redesign this so that the function you are invoking returns a List<Filenames> (or just an IEnumerable<Filenames> to be less specific) and let the form class worry about filling its filenamesList property. Exposing data members of a form can get messy quickly since you need to pass an instance of the form to anything that must use the property.
soimething like this:
-- other class --
public IEnumerable<Filenames> GetFilenames()
{
return new List<Filenames> { new Filenames { name = "filename1", id = 1 } };
}
--MainForm--
this.filenamesList.Clear();
this.filenamesList.AddRange(otherclass.GetFilenames());
When you do this in the second form:
MainForm mainForm = new MainForm();
You've created an entirely new instance of MainForm that has no reference to the list in the original MainForm instance. You're clearing the list and adding items to it, but when you exit your second form those items are lost.
You've got to pass your original MainForm instance to the new form that opens:
public class Form2 : Form
{
private MainForm mainForm;
public Form2(MainForm mainForm)
{
this.mainForm = mainForm;
}
public void SomeMethodThatUpdatesFileNamesList()
{
mainForm.filenamesList.Clear();
...
}
}
By declaring a new MainForm using the line MainForm mainForm = new MainForm(); you are not referring to the same filenamesList. You need to get the reference to the first class, either by sending the filenamesList as a parameter to the function or by adding it as a propery in one of the classes.
If the "other class" is a child of the main form, you might be able to get a reference to the parent object, but this depends on the stucture of the program.

Updating text box from another class

I'm trying to update a text box from a class called 'hex' to the main form. Within the class 'hex' I have the following code:
Main m = new Main();
m.updateTextBox(convertedHex);
the code passed the variable to the main form to the method called 'updateTextBox' as shown below:
public void updateLog(string input)
{
textBox2.AppendText(input);
}
Sorry if this seems like a silly questions I have been stuck for a while, all the links on my google searches are now purple so I was hoping if someone could explain this to me. Many thanks.
Add this kind of method inside your Main class where textBox is created and call it from outside.
Lets say you added the code in your Program.cs class to start new
// Add this code in Program.cs (or similar where you start the gui
public static readonly Main MainLogWindow = new Main();
// Add this code in Main.cs class
private delegate void NameCallBack(string varText);
public void UpdateTextBox(string input) {
if (InvokeRequired) {
textBox.BeginInvoke(new NameCallBack(UpdateTextBox), new object[] {input});
} else {
textBox.Text = input;
// textBox.Text = textBox.Text + Environment.NewLine + input // This might work as append in next line but haven't tested so not sure
}
}
Call it like: Program.MainLogWindow.UpdateTextBox("test test"); from anywhere assuming that you have MainLogWindow open
This will also allow you to call updates from within other threads.
You have not given us very much information to go on. But as I said in my comment if your startup form is Main, the code that you are showing is creating a new Main Form and any changes made to it will not appear in your UI. You need to pass the form instance to the Hex class constructor. I would do something like this(assuming that the namespaces are the same, they are on the same thread, and your Hex Class is not Static. if on different threads you need to use the Method shown by MadBoy)
public partial class Form1 : Form
{
Hex hex;
public Form1()
{
InitializeComponent();
hex = new Hex(this);
}
}
class Hex
{
Form1 m;
public Hex( Form1 frm)
{
m = frm;
m.updateTextBox("Hello World");
}
}
Your class, presumably a business object, generally shouldn't be concerned with updating the UI. It doesn't particularly need to know that you even have a UI. But there are a couple of different useful approaches you could use.
1) Simply have your UI invoke your business object's method, and let the method return a value, and then the UI can choose to display it.
// inside Main form
var hex = new Hex();
string convertedHex = hex.GetConvertedHex(someArgument);
UpdateTextBox(convertedHex);
2) Have your business object expose an event. The arguments for the event would include whatever string that needs to be broadcast to whomever subscribes to the event. The UI would then be one of the subscribers.
Of the two ideas, I would generally opt for the first unless you actually do need an event model.
jest simple no need to do all of this make text box public from the properties and pass the current form object to the class throudh a method like this
public void mthod(){
//crete a obj of the class
cls1 obj=new clas1();
obj.smethod(this);
}
now in the class can cal it like this
smethod(from1 obj){
obj.textbox.text="";
}

C# WinForms - How Do i Retrieve Data From A Textbox On One Form Via Another Form?

I have a method that executes inside one form, but I need to retrieve data from another form to pass into the method.
Whats the best way of doing this?
You can expose a property on one form and call it from the other. Of course you'll need some way of getting the instance of form1. You could keep it as a static property in the program class or some other parent class. Usually in this case I have a static application class that holds the instance.
public static class Application
{
public static MyForm MyFormInstance { get; set; }
}
Then when you launch the first form, set the application MyFormInstance property to the instance of the first Form.
MyForm instance = new MyForm();
Application.MyFormInstance = instance;
Add a property to the second form.
public String MyText
{ get { return textbox1.Text; }
set { textbox1.Text = value; }
}
And then you can access it from your second form with:
Application.MyFormInstance.MyText
On the form that has the textbox you need data from, expose either a Property or a Method that returns the text. IE:
internal string TextBoxTest
{
get{ return this.textBox1.Text;}
}
There is a similar post here
The videos below will clear up a lot of your concepts about passing data between 2 forms.
There are multiple ways to pass data between 2 forms check these links which has example videos to do this
FormToForm Using Properties - http://windowsclient.net/learn/video.aspx?v=108089
FormToForm Using Parameters - http://windowsclient.net/learn/video.aspx?v=105861
HTH
Assuming that formB is initialized in formA I would recommend adding a string to the constructor of formB sending the Texbox1.Text
as in
class formB: Form{
private string data;
public formB(string data)
{
InitializeComponent();
this.data = data;
}
//rest of your code for the class
}
Don't do this.
Longer version: Why is your view directly interacting with another view?
Much longer version:
Rather than making a public property that exposes the field, it would provide better encapsulation and insulation from change if the form with the field of interest interacted with some form of data object, which was then passed to the interested method.
The location of the interested method should be carefully considered - if it controls aspects of the view (WinForm, in your case), then it may be appropriately a member of that class - if not, perhaps its real home is in the data object?

Categories

Resources