Reputation: 157
I have a windows form (c#). In the form, the user inputs some text and it then gets saved to an XML. Each time the solution starts, it reads the XML.
At first, I was just testing so I had a master class. Then I started creating different classes and run into a problem. I can't access the values from the textboxes of the form from the other classes. There are a few other posts asking the same, but I couldn't manage to solve it.
This is what I have:
namespace Emailing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
XmlController xc = new XmlController();
xc.readXml(); //reads the xml when starts
}
private void button1_Click(object sender, EventArgs e)
{
XmlController xc2 = new XmlController();
xc2.updateXml(); //updates the xmls when the users clicks a button
}
}
}
namespace Emailing
{
class XmlController
{
public void updateXml()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "Server";
dt.Columns.Add("Server");
ds.Tables.Add(dt);
DataRow row = ds.Tables["Server"].NewRow();
row["Server"] = Form1.textBox6.Text;
ds.Tables["Server"].Rows.Add(row);
ds.WriteXml("Emailer.xml");
}
public void readXml()
{
DataSet ds = new DataSet();
ds.ReadXml("Emailer.xml");
Form1.textBox6.Text = ds.Tables["Server"].Rows[0][0].ToString();
}
}
}
I tried several things with no success. From what I read, the "best" practice would be to create an interface. I tried but couldn't make it work. I also tried creating a get set method for the textBox but couldn't make it work. I'm not sure where it should go.
Thanks for your time,
Upvotes: 1
Views: 74
Reputation: 3433
If you want to access something from "outside" of a class (the form is a class), you need it to be Public.
Edit:
namespace Emailing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
}
public string TextOfTextBox1 { get { return Textbox1.Text; } }
}
}
If you have, lets say a 'LoginForm',
You might want to add a property to fetch the given Username as public string UserName { get { return userNameTextBox.Text; } }
(same for the Password, Remmember me, Etc...)
Upvotes: 0
Reputation: 200
You have instantiated the XmlController class 2 times.
this means that you have 2 objects of the same class, but it are different objects.
what you should do is instantiate the class once and use this object also for the button_Click event (see code)
namespace Emailing
{
public partial class Form1 : Form
{
private XmlController xc;
public Form1()
{
InitializeComponent();
xc = new XmlController();
xc.readXml(); //reads the xml when starts
}
private void button1_Click(object sender, EventArgs e)
{
xc.updateXml(); //updates the xmls when the users clicks a button
}
}
}
however I do suggest you start experimenting with the MVVM pattern see: https://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
Upvotes: 1