Still in the process of learning C#, but I'm a bit confused on something here.
For example, I have a textbox on my form and it has the name of testTXT. Based on the code below, I've created a new class outside of the public partial one that's there by default, and now I'm trying to access testTXT but I cannot. I'm going to also need to access several other textboxes and things later on as well.
Here's a snippet of the code I'm working with thus far:
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass();
gc.CreatePackage("C:\\Users\\user\\Downloads\\output.docx");
}
private void browseButton_Click(object sender, EventArgs e)
{
var fsd = new FolderSelect.FolderSelectDialog();
fsd.Title = "Select folder to save document";
fsd.InitialDirectory = #"c:\";
if (fsd.ShowDialog(IntPtr.Zero))
{
testTXT.Text = fsd.FileName;
}
}
}
public class GeneratedClass
{
**trying to access testTXT right here, but can't.**
}
}
Any help would be greatly appreciated.
You could do this (see other answers), but you really shouldn't.
Nobody but the containing form has to know about the textboxes in it. Who knows, they might disappear, have their name changed, etc. And your GeneratedClass could become a utility class used by lots of forms.
The appropriate way of doing this, is to pass whatever you need from your textbox to your class, like so:
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass();
gc.CreatePackage(this.testTxt.Text);
}
public class GeneratedClass
{
public void CreatePackage(string name) { // DoStuff! }
}
This is because you have your TextBox type defined in Form1 class as private member. Thus can't be access with another class instance
Your question has little to do with C#, more to do with Object Oriented Concepts.
Instance of TextBox has to be given to 'GeneratedClass' somehow.
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass(testTXT);
gc.DoSomething();
gc.CreatePackage("C:\\Users\\user\\Downloads\\output.docx");
}
private void browseButton_Click(object sender, EventArgs e)
{
var fsd = new FolderSelect.FolderSelectDialog();
fsd.Title = "Select folder to save document";
fsd.InitialDirectory = #"c:\";
if (fsd.ShowDialog(IntPtr.Zero))
{
testTXT.Text = fsd.FileName;
}
}
}
public class GeneratedClass
{
TextBox _txt;
public GeneratedClass(TextBox txt)
{
_txt= txt;
}
public void DoSomething()
{
txt.Text = "Changed the text";
}
}
}
You must make testTXT public.
See Protection level (Modifiers) of controls change automaticlly in .Net.
And access to TextBox as
public class GeneratedClass
{
GeneratedClass(Form1 form)
{
form.testTXT.Text = "1";
}
}
Related
I am learning C# and have run into an interesting issue to me. I have a class variable defined as public and I instantiate a new instance of my form in my class and access the value of the public variable it is always null.
To further explain my issue - this syntax prints the appropriate value
System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
However, this syntax is always outputting a 0
System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
How do I need to alter my syntax so that the correct value is passed to the class Functions?
public partial class Form1 : Form
{
public double tboxvalue;
private string exportdata;
public Form1()
{
InitializeComponent();
}
private void btnClicker_Click(object sender, EventArgs e)
{
Functions.EE();
}
private void txtData_CheckedChanged(object sender, EventArgs e)
{
bool #checked = ((CheckBox)sender).Checked;
if (#checked.ToString() == "True")
{
exportdata = "Yes";
tboxvalue = Convert.ToDouble(this.txtData.Text);
System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
}
else
exportdata = "No";
}
}
class Functions
{
public static void EE()
{
Form1 f1 = new Form1();
System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
}
}
To access properties of the form, you need to change two Things. First you have to pass the form to the 'EE' method, then you can access the form's properties. Second, don't create a new form in 'EE' method.
public partial class Form1 : Form
{
public double tboxvalue;
private string exportdata;
public Form1()
{
InitializeComponent();
}
private void btnClicker_Click(object sender, EventArgs e)
{
Functions.EE(this);
}
private void txtData_CheckedChanged(object sender, EventArgs e)
{
bool #checked = ((CheckBox)sender).Checked;
if (#checked.ToString() == "True")
{
exportdata = "Yes";
tboxvalue = Convert.ToDouble(this.txtData.Text);
System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
}
else
exportdata = "No";
}
}
class Functions
{
public static void EE(Form1 f1)
{
System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
}
}
If i understood your question i guess you are recreated Form1 with own textbox or labels when you click btnClicker button. You can reassign your form objects where you created it.
You might add static Form1 object and Setter routine to Functions class:
private static Form1 _form;
public static void SetForm(Form1 form)
{
_form = form;
}
and pass the form to the class in Form_Load event-click on the form twice:
private void Form1_Load(object sender, EventArgs e)
{
Functions.SetForm(this);
}
Then you can play with the form in Functions class using the object _form
good luck!
I have a simple Windows Form with a button and textbox. I want the textbox to update with some string when the button is pressed. I know the following works:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.text = "some string";
}
}
I also know, that the following will work. This gives me a bit more freedom, cause I can easily decide what I want to appear in the textbox:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
updateText("some string");
}
public void updateText(string s)
{
textBox1.Text = s;
}
}
Now, let's say that my code is getting big, and I want to keep things tidy. I want to move my code that performs updates into a different class called Updates. In that class I want to have a method that I can run on any textBox with any string. When I try the following, I get an error: The name 'textBox1' does not exist in the current context.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Updates.updateText("some string");
}
}
public class Updates
{
public void updateText(string s)
{
textBox1.Text = s;
}
}
I have seen more complex questions here about similar things, but I can't get their solutions to work. I think I'm missing something basic.
Additionally, I don't know how I would expand this method to accept any textBox, e.g.:
public void updateText(??? target, string s)
{
target.Text = s;
}
What type would target take?
Change your function to accept TextBox like this:
public void updateText(TextBox target, string s)
{
target.Text = s;
}
Samvel Petrosov answer is best solution, but if you would like to have another option, there it is: set the text box modifier to public (or internal), add reference to your form in Updates class. Then you will be able to modify it (text box) freely.
I have seen a few links on attempts at this but I haven't found a solution. I am attempting to access my form textbox and update it with text from another class. I can update the text within my DataOrganizerForm class directly but when I pass text back to the DataOrganizerForm class then it doesn't update on the GUI. Here is what I have:
public partial class DataOrganizerForm : Form
{
//Default constructor
public DataOrganizerForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//Handle a Start/Stop button click
private void start_stop_button_Click(object sender, EventArgs e)
{
SerialNumberSearcher snsearch = new SerialNumberSearcher();
snsearch.searchSN();
}
//Allow simple access to update to notification textbox
public void setNotificationText(string text)
{
notification_textbox.Text = text;
}
}
public class SerialNumberSearcher
{
public void searchSN()
{
DataOrganizerForm formAccess = new DataOrganizerForm();
formAccess.setNotificationText("Updated text from different class");
}
}
Well, it won't update the textbox 'cause you're instantiating another object of the DataOrganizerForm class. What you could do is passing a reference of the form object to the SerialNumberSearcher, like this:
public class SerialNumberSearcher
{
private readonly DataOrganizerForm _form;
public SerialNumberSearcher(DataOrganizerForm form)
{
_form = form;
}
public void searchSN()
{
_form.setNotificationText("Updated text from different class");
}
}
You need to understand at which instance you operate. When you use the new-eperator you create a new instance, like a new copy of that type.
DataOrganizerForm formAccess = new DataOrganizerForm();
The original Form is a different instance then the one you create in the searchSN method.
You need to pass that instance into the method to manipulate it:
public void searchSN(DataOrganizerForm formAccess )
{
formAccess.setNotificationText("Updated text from different class");
}
When you want to call this method you need to use this to reference the current object :
private void start_stop_button_Click(object sender, EventArgs e)
{
SerialNumberSearcher snsearch = new SerialNumberSearcher();
snsearch.searchSN(this);
}
this will access the current instance of the Form, thereby allowing you to manipulate the textbox that you are interested in.
When do you use the “this” keyword? might also be helpfull
Thanks for the help. This is what I was able to do to make my application work. I passed the Textbox object by reference to my other class and was able to display my information that way. Also, I had issues getting my text box to continuously update. I had to add
public partial class DataOrganizerForm : Form
{
//Default constructor
public DataOrganizerForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//Handle a Start/Stop button click
private void start_stop_button_Click(object sender, EventArgs e)
{
SerialNumberSearcher snsearch = new SerialNumberSearcher();
snsearch.searchSN(notification_textbox);
}
//Allow simple access to update to notification textbox
public void setNotificationText(string text)
{
notification_textbox.Text = text;
notification_textbox.Update();
}
}
public class SerialNumberSearcher
{
public void searchSN(Textbox notifyTextbox)
{
notifyTextbox.setNotificationText = "Updated text from different class";
notifyTextbox.Update();
}
}
{
public partial class form1 : Form
{
public form1()
{
InitializeComponent();
}
public Button ButtonName { get { return } }
public static int initFaggleCount;
private void button1_Click(object sender, EventArgs e)
{
int faggleCount = initFaggleCount++;
string finalCalc = faggleCount.ToString();
label1.Text = finalCalc;
/*
Console.WriteLine(faggleCount);
Console.ReadLine();*/
}
private void button2_Click(object sender, EventArgs e)
{
/*TextWriter tw = new StreamWriter("SavedFaggleCount.txt");
tw.WriteLine();
tw.Close();*/
Console.WriteLine(faggleCount);
Console.ReadLine();
}
}
}
I would like the integer faggleCount to be accessible from button2 so that I can successfully Console.WriteLine(fagleCount); from button2. I'm a noob and any help is appreciated. Thanks!
instead of declaring local variable inside method body you can declare instance variable so that all members of class can access it.
public partial class form1 : Form
{
int faggleCount; //declare instance variable.
public form1()
{
InitializeComponent();
}
public Button ButtonName { get { return } }
public static int initFaggleCount;
private void button1_Click(object sender, EventArgs e)
{
faggleCount = initFaggleCount++; //use instance variable
string finalCalc = faggleCount.ToString();
label1.Text = finalCalc;
/*
Console.WriteLine(faggleCount);
Console.ReadLine();*/
}
private void button2_Click(object sender, EventArgs e)
{
/*TextWriter tw = new StreamWriter("SavedFaggleCount.txt");
tw.WriteLine();
tw.Close();*/
Console.WriteLine(faggleCount); //use instance variable
Console.ReadLine();
}
}
In your code, faggleCount is local to the method i.e. only code in the method can access it. What you need to do is to move the variable to the class-level. like this:
public class form1 : Form {
int faggleCount;
//your other code here
}
As you can see, the variable is now in the class, not in the method. This way all the methods in the class can access it, and even a inner class can access it too!
This problem is very common among beginners. Understanding the scope of the variable is pretty hard. In short, A variable in a class can be accessed in the class, a variable in a method can be accessed in the method.
i have a really simple counter application, I made in C#.
Now what i want to know is it possible to clone the form design and code, so there are 2 counter's instead of one. with a button.
they both have to be working.
i'm an beginner.. so that's why i ask if this is possible.
So from this (this is what i currently have, without clone button):
http://i.stack.imgur.com/ASMY4.jpg
to this:
http://i.stack.imgur.com/acluZ.jpg
this is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void counteradd()
{
int current1 = Convert.ToInt32(totaltb.Text);
current1++;
totaltb.Text = Convert.ToString(current1);
}
public void counterreduce()
{
int current2 = Convert.ToInt32(totaltb.Text);
current2--;
totaltb.Text = Convert.ToString(current2);
}
public void counterreset()
{
totaltb.Text = ("0");
}
private void reducebttn_Click(object sender, EventArgs e)
{
counterreduce();
}
private void resetbttn_Click(object sender, EventArgs e)
{
counterreset();
}
private void addbttn_Click(object sender, EventArgs e)
{
counteradd();
}
}
Simply duplicating the controls and laying them out on the form will result in messy code. The "clone' that you are referring to would be to build the functional piece as a user-control, and then add that as a control to your form.