How to pass a string to child form? - c#

Basically what I'm trying to do is I have a string on the main form that pulls its value from a textbox.
I then generate a modal version of a second form and want to have that string (or the main forms textbox1.text value) usable in the second form for processes.
Main Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace Tool{
public partial class MainForm : Form
{
public string hostname;
public MainForm()
{
InitializeComponent();
textBox1.Text = hostname;
}
public void btn_test_Click(object sender, EventArgs e)
{
string hostname = textBox1.Text;
SiteForm frmsite = new SiteForm();
frmsite.ShowDialog();
}
}
}
'
Child Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace Tool
{
public partial class SiteForm : Form
{
public string hostname {get; set; }
public SiteForm()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
label1.Text = this.hostname;
}
}
}
Any suggestions on how I can do this? I know there has to be a simpler way, sorry I'm still a bit of a noob and am trying to teach myself C# as I go.
The result is when I click the label on the child form it is blank, because of this I am able to deduce that the string isn't passing between the two forms correctly.

The simplest way is to pass it in the constructor of the Child form, for example:
private string _hostname = "";
...
public SiteForm(string hostname)
{
_hostname = hostname;
InitializeComponent();
}

Try hooking into your child form's Load event and set the value of its hostname property in an event handler on your main form.
public void btn_test_Click(object sender, EventArgs e)
{
string hostname = textBox1.Text;
SiteForm frmsite = new SiteForm();
frmsite.Load += new EventHandler(frmsite_Load);
frmsite.ShowDialog();
}
public void frmsite_Load(object sender, EventArgs e)
{
SiteForm frmsite = sender as SiteForm;
frmsite.hostname = this.hostname;
}

Related

Call a Get Method from Another Form, C#

I am sorry if my question is silly , I am a beginner.I have two forms:
Form1: Displays a Table of Information
Form2: Displays a Form to Fill information
I need to get the information in Form2 to Form1 Using get methods (If there is a better way please suggest it).
My problem is that when I type those get methods in Form1 they are not recognized.
Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//---------------------------------Initial Stuff------------------------------------
Form2 form2 = null;
//----------------------------------Constructor-------------------------------------
public Form1()
{
InitializeComponent();
}
private void nouveau_Click(object sender, EventArgs e)
{
if (form2 == null)
{
form2 = new Form2();
form2.Show();
}
}
//---------------------------------ListView of Information------------------------------
ListViewItem lvi = new ListViewItem(getClient());
lvi.SubItems.Add(societe.Text);
lvi.SubItems.Add(datedebut.Text);
lvi.SubItems.Add(type.Text);
lvi.SubItems.Add(etat.Text);
}
}
Form2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 :
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
client.Text="";
societe.Text = "";
datedebut.Text = "";
type.Text = "";
etat.Text = "";
}
//----------------------------Return Functions for table----------------------
public String getClient()
{
return client.Text;
}
public String getSociete()
{
return societe.Text;
}
public String DateDebut()
{
return datedebut.Text;
}
public String getType()
{
return type.Text;
}
public String getEtat()
{
return etat.Text;
}
}
}
So I update my code and tried another way to do things
Now I have 4 .cs files: Principal, FillInfo, Folder, Program
Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Principal());
}
}
}
Folder:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class Folder
{
//-----------------------------------------CONSTRUCTOR--------------------------
public Folder()
{
this.Customer = "";
this.Company = "";
this.StartDate = "";
this.TechUsed = "";
this.Status = "";
}
//-----------------------------------------GETTERS AND SETTERS-------------------
public string Customer { get; set; }
public string Company { get; set; }
public string StartDate { get; set; }
public string TechUsed { get; set; }
public string Status { get; set; }
}
}
Principal:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Principal : Form
{
//-----------------------------------INITIAL VARIABLES--------------------------------------------------
FillInfo fillinfo = null;
public Folder f;
//-----------------------------------INITIAL METHODS----------------------------------------------------
public Principal()
{
InitializeComponent();
}
//-----------------------------------ELEMENTS METHODS--------------------------------------------------
// NEW BUTTON
private void pNew_Click(object sender, EventArgs e)
{
f= new Folder();
if (fillinfo == null)
{
fillinfo = new FillInfo();
fillinfo.Show();
}
}
//---------------------------------------PROCESSING-----------------------------------------------------
ListViewItem fillInfoListView = new ListViewItem(f.getCustomer());
}
}
FillInfo:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class FillInfo : Form
{
//-----------------------------------INITIAL VARIABLES--------------------------------------------------
//-----------------------------------INITIAL METHODS----------------------------------------------------
public FillInfo()
{
InitializeComponent();
}
//-----------------------------------ELEMENTS METHODS--------------------------------------------------
private void fOkButton_Click(object sender, EventArgs e)
{
f.setCustomer = fCustomerTextField.Text;
f.setCompany = fCompanyTextField.Text;
f.setStartDate = FStartDateDatePicker.Text;
f.setTechUsed = fTechUsedDropList.Text;
f.setStatus = fStatusDropList.Text;
fCustomerTextField.Text = "";
fCompanyTextField.Text = "";
FStartDateDatePicker.Text = "";
fTechUsedDropList.Text = "";
fStatusDropList.Text = "";
}
}
}
Assuming Form2 is something that appears and asks the user for info, then disappears when the user is done typing into it, it would probably look like:
private void nouveau_Click(object sender, EventArgs e)
{
var form2 = new Form2();
form2.ShowDialog(); //SHOW DIALOG
ListViewItem lvi = new ListViewItem(getClient());
lvi.SubItems.Add(form2.Societe); //the property you are busy writing
lvi.SubItems.Add(form2.DateDebut); //the property you are busy writing
lvi.SubItems.Add(form2.Type); //the property you are busy writing. Try and think of a more hepful name than Type
lvi.SubItems.Add(form2.Etat); //the property you are busy writing
//do you need to add that lvi to something?
}
Remove Form2 from being a class level variable

visual studio open link seperate form

Basically trying to learn a few things I havn't tried yet. I want to make a small program that has a Textbox and Button.
Whats typed into the textbox field will be added to the end of a url applied from the button.
http://website.com/stuff?things= +textboxValue
After you click the launch button, I want the url created with the entered text, to open in a second form.
I have everything working except for the text from form1 to carry over to form2. Just wondering how I can go about this.
Form 1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.LinkTarget = textBox1.Text;
form2.Show();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Form3 newFrm = new Form3();
newFrm.Show();
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
}
Form2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string LinkTarget {
get;
set;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string myUrl = "http://website.com/stuff?things=" + LinkTarget;
}
}
}
Example of what I am going for.
Form one has text box and button.
when you click the button it will open http://www.stackoverflow.com/questions/ in the second form. the second form is basically a browser.
but, in form one if I type 41090977 before I hit the button, it will open http://www.stackoverflow.com/questions/41090977
You can create a property in form2, which you set before you open it:
//... other form2 code
public string LinkTarget {
get;
set;
}
You can set the value like this (in button1_Click):
Form2 form2 = new Form2();
form2.LinkTarget = myTextBox.Text;
form2.Show();
Within form2 you can use the value of the property to create your link. In your current code you have just defined the property. You have to use its content to create your link. This is done by attaching the property value to your string containing the URL with the + operator:
string myUrl = "http://website.com/stuff?things=" + LinkTarget;

Why does the following code produce Object Disposed Exception

I am playing around in visual studio and getting to know C# better. I am coming from an intermediate background knowledge of Java.
I have produced a very simple windows form application. The user clicks on a button, the button takes them to another screen, the user types into a textbox and presses a button in which that button will display what the user typed in; in the form. This is the code:
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
Form2 userinputForm;
public Form2 getSetForm2 {
get { return userinputForm; }
set { userinputForm = value; }
}
Form1 homeFormObj;
public Form1 getSetForm1 {
get { return homeFormObj; }
set { homeFormObj = value; }
}
public Form1()
{
InitializeComponent();
getSetForm2 = new Form2();
getSetForm1 = this;
getSetForm2.formOnePublicObj = getSetForm1;
}
internal void displayUserInput(string name)
{
Label l = new Label();
l.Text = name;
panel1.Controls.Add(l);
}
private void button1_Click(object sender, EventArgs e)
{
userinputForm.Show();
}
}
}
Form2.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form2 : Form
{
Form1 formOneObj;
public Form1 formOnePublicObj {
get { return formOneObj; }
set { formOneObj = value; }
}
public Form2()
{
InitializeComponent();
}
List<string> userinputs = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
formOnePublicObj.displayUserInput(name);
}
}
}
The error occurs the second time the user presses the button to go to form2. it occurs on the .show() method.
(P.S I coded like this to see how I can pass data from one windows form to another hence the getters and setters on the form objects).
Well, userinputform is never set and so is null. As such I don't understand why it works the first time unless this isn't actually your code pasted in.
It's probably because you're closing the second form, which is destroying it therefore you can't show it again. Each time you click the button in form1 create a new form2:
getSetForm2 = new Form2();
getSetForm1 = this;
getSetForm2.formOnePublicObj = getSetForm1;

C# get set error

This Form 1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using Managed.Adb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
AndroidDebugBridge mADB;
String mAdbPath;
List<Device> devices = AdbHelper.Instance.GetDevices(AndroidDebugBridge.SocketAddress);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e )
{
//mAdbPath = Environment.GetEnvironmentVariable("PATH");
mAdbPath = "C:\\Users\\Nadun\\AppData\\Local\\Android\\android-sdk\\platform-tools";
mADB = AndroidDebugBridge.CreateBridge(mAdbPath + "\\adb.exe", true);
mADB.Start();
var list = mADB.Devices;
textBox1.Text = "" + list.Count;
foreach (Device item in list)
{
Console.WriteLine("");
listBox1.Items.Add("" + item.Properties["ro.build.product"].ToString() + "-" + item.SerialNumber.ToString() );
}
//Console.WriteLine("" + list.Count);
}
private void button2_Click(object sender, EventArgs e)
{
string text = listBox1.GetItemText(listBox1.SelectedItem);
Form2 f2 = new Form2(text);
// f2.Phone = "scs";
SetPhone sp = new SetPhone();
sp.PhoneModel = "Test";
this.Visible = false;
f2.ShowDialog();
}
}
}
This is Form 2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private string phone;
public string Phone
{
get { return this.phone; }
set { this.phone = value; }
}
public Form2(string a)
{
InitializeComponent();
textBox1.Text = a;
}
private void Form2_Load(object sender, EventArgs e)
{
//Form2 f2 = new Form2();
//f2.phone = "s";
//textBox1.Text = f2.Phone;
SetPhone sp = new SetPhone();
textBox1.Text = sp.PhoneModel;
Console.WriteLine("sefsef-"+sp.PhoneModel);
}
}
}
This is my Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
class SetPhone
{
private string phoneModel;
public string PhoneModel {
get { return this.phoneModel; }
set { this.phoneModel = value; }
}
}
}
Get always returning empty.i don't know why.
I am trying to set values from "form1".
i wrote class for that as well.but when i getting values from "form2" it returning empty.i don't know why
Your SetPhone class object which is calling the setter in the button2_click is a local variable, so when you try access the same in Form2_Load using another local variable, it is a completely new object and Get returns an empty string (default value). You should be able to share the SetPhone variable across forms, may be using constructor, then it will retain the values set using the setter

How to change user control label.text from a form

Right so I have a user control called "ModbusMaster" and a form with literally a single button on it..
When I click the button I want to change the text of a label on my control..
However nothing happens..
Here is the main form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ModbusMaster_2._0
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ModbusMaster mb = new ModbusMaster();
public void button1_Click(object sender, EventArgs e)
{
mb.openPort("wooooo");
}
}
}
I am calling the method openPort and passing the string "wooo" to it..
here is my control
The text does not get updated :(:(:(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace ModbusMaster_2._0
{
public partial class ModbusMaster : UserControl
{
string portName = "COM1"; //default portname
int timeOut = 300; //default timeout for response
SerialPort sp = new SerialPort();
public ModbusMaster()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
portLabel.Text = portName;
}
public void openPort(string port)
{
statusLabel.Text = port;
}
/*
* Properties
*/
public string SerialPort //Set portname
{
get { return portName; }
set { portName = value;}
}
public int TimeOut //Set response timeout
{
get { return timeOut; }
set { timeOut = value; }
}
}
}
I think you must have two instances of ModbusMaster.
One of them is the one you can see on the display, and is NOT being updated.
The other one is the one you create in class Form1 with the line of code:
ModbusMaster mb = new ModbusMaster();
That is the one you are modifying, but it isn't the displayed one (I cannot see anywhere that you can be displaying that).
What you need to do is use the reference to the actual displayed one instead when you call mb.openPort("wooooo");
[EDIT]
Thinking about it - it's possible that you haven't instantiated another user control at all.
Did you use Visual Studio's Form Designer to add the user control to your main form? I had assumed that you did, but now I realise that might not be the case.
If not, you should do that, give it the name mb and remove the line that says ModbusMaster mb = new ModbusMaster(); and it might work without you having to make more extensive changes.
You are creating your UserControl but not assigning it to your Form's Control Collection. Try something like this in your Constructor.
namespace ModbusMaster_2._0
{
public partial class Form1 : Form
{
ModbusMaster mb = new ModbusMaster();
public Form1()
{
InitializeComponent();
this.Controls.Add(mb); //Add your usercontrol to your forms control collection
}
public void button1_Click(object sender, EventArgs e)
{
mb.openPort("wooooo");
}
}
}

Categories

Resources