I have the following method
public partial class formTabelasPsi : Form
{
private Form1 Opener { get; set; }
public formTabelasPsi(Form1 opener)
{
this.Opener = opener;
InitializeComponent();
}
public static void publicmethod1(string path)
{
//some code related to path
}
}
I want publicmethod1 to check a checkbox whenever this formTabelasPsi runs it.
I tried to specify it using formTabelasPsi.checkBox1.Checked = true; but the code says a object reference is required.
Maybe this is a newbiez question for most of you, but honestly, as a amateur programmer I didn't find this clearly anywhere.
The checkbox belongs to an instance of that form, you need to reference that instance in order to update it
public void publicmethod1(string path)
{
this.checkBox1.Checked = true;
}
The method also needs to belong to an instance of the form, you can find out more about instances here
Related
TF2SelectDir.txtTF2DirSelect.Text = "";
This is giving me issues, as txtTF2DirSelect is on one form and I'm trying to change it from another. I tried looking it up, and the entire form itself is already public, not private.
Or, to go along with this, how can I create a variable that can be accessed on any form?
Where it goes wrong
if (canFindTF2 == true)
{
TF2SelectDir.txtTF2DirSelect.Text = "";
The form where TF2SelectDir is is already public
public partial class TF2SelectDir : Form
{
public TF2SelectDir()
{
InitializeComponent();
}
Any ideas? Thanks!!
UPDATE
At the bottom of my TF2SelectDir.Designer.cs, I've found
private System.Windows.Forms.TextBox txtTF2DirSelect;
private System.Windows.Forms.Button btnSaveTF2Dir;
private System.Windows.Forms.Label lblExample;
However, when I changed private to public on txtTF2DirSelect, I got a new error.
"An object reference is required for the non-static field, method, or property 'TF2SelectDir.txtTF2DirSelect' - Error Code CS0120
Since I cannot comment, I am posting this as an answer.
Accessing controls from a separate form, may not be the best idea. I would recommend you use properties. Here is Microsoft's definition and usage example of properties.
Another, even better way, in my opinion, to share data between two forms, is to use events. Once again, here is Microsoft's description of events.
If you need a working example of how to use either of these approaches, I would like to see your effort first and then we can build on that.
Expose control in below way .. why?? #monstertjie_za provided few good links on that already .
namespace TF2Overwatch
{
public partial class TF2SelectDir : Form
{
//Approch 1 - usable when the projects most works are done
//without following a good architecture
//You can use a static variable to preserve the state and intilize each time
//a new instance is created
//Approch 2 - Responibilty of preserving text to initlize in textbox should be taken
//by the form who calling this form
//value will pass by consturtor or by exposing property
//all approch 2 code are kept commented for better understanding
private static string strTxtTF2DirSelectTextToInitize;
public TF2SelectDir()
{
InitializeComponent();
txtTF2DirSelect.Text = strTxtTF2DirSelectTextToInitize;
}
public static string TxtTF2DirSelectTextToInitlize
{
get
{
return strTxtTF2DirSelectTextToInitize;
}
set
{
strTxtTF2DirSelectTextToInitize = value;
}
}
//public TF2SelectDir(string txtTF2DirSelectText)
//{
// InitializeComponent();
// txtTF2DirSelect.Text = txtTF2DirSelectText;
//}
//public string TxtTF2DirSelectTextToInitlize
//{
// get
// {
// return txtTF2DirSelect.Text;
// }
// set
// {
// txtTF2DirSelect.Text = value;
// }
//}
}
public partial class SomeAnotherForm:Form
{
public SomeAnotherForm ()
{
InitializeComponent();
}
protected void InSomeAction(object Sender, EventArgs e)
{
if (canFindTF2 == true)
{
TF2SelectDir.TxtTF2DirSelectText = "Test";
TF2SelectDir t1 = new TF2SelectDir();
t1.Show();
//Approch 2
//TF2SelectDir t1 = new TF2SelectDir("Test");
//t1.Show();
//TF2SelectDir t1 = new TF2SelectDir();
//t1.TxtTF2DirSelectText="Test"; //look here TxtTF2DirSelectText is setting on instance not by class
//t1.Show();
}
}
}
}
I am very new to C# coding, so this may be very simple. In my Site.Master.cs, I have the following code:
GetLoggedInUserProperties();
lblLoginUser.Text = string.Format("Welcome {0}", Session[SessionVars.UserName]);
In a class file, I have put the following in a Public Class:
void GetLoggedInUserProperties()
{
string sLoginId = Program.ExtractUserName(HttpContext.Current.Request.ServerVariables["LOGON_USER"]);
HttpContext.Current.Session[SessionVars.LoginId] = sLoginId;
VerifyInAD(sLoginId);
}
There are no errors in the class file, but my Site.Master.cs cannot find the code in the class file.
I am sure there is a better way to do this, so feel free to let me know. Also, the lblLoginUser does not seem to work either. It has the same error. I have tried recreating the label and deleting the designer file (which never came back). Not sure if this is related or not.
Thank you.
You need to make your methods public or protected to be visible from the markup. So if you want to reference GetLoggedInUserProperties() from the markup, you'll need to change your method declaration to something like this.
protected void GetLoggedInUserProperties()
{
}
Make your method public
Here your class
public class ClassName
{
public void GetLoggedInUserProperties()
{
}
}
public MainWindow()
{
InitializeComponent();
ClassName instance = new ClassName();
instance.GetLoggedInUserProperties();
}
Or make your class static and call your method :
public static class ClassName
{
public static void GetLoggedInUserProperties()
{
}
}
public MainWindow()
{
InitializeComponent();
ClassName.GetLoggedInUserProperties();
}
I'm wondering if it is possible to access a textbox value from another class inside a C# winform.
For example, at the moment I have a bunch of different textboxes I'm turning on and off all within my Form1.cs class like so:
screentextBox.Visible = true;
However, to cut down on the amount of lines of code within my C# class I was wondering is it possible to make this call from another class, then in my Form1.cs call my other classes method?
Something like:
class Otherclass
{
public void ShowTextBox()
{
screentextBox.Visible = true;
}
}
Then in my Form1.cs simply call my new ShowTextBox method.
I'm sorry if this is a silly question, but I've looked around google and I couldn't find anything that could help me out.
You could pass the TextBox as a parameter to a function in another class:
class OtherClass
{
public void ShowTextBox(TextBox target)
{
target.Visible = true;
}
}
However, I would advise to keep all the methods and code pertaining to handling the GUI and its events inside the form itself. If you have large methods for calculations, etc., than those can be moved to other classes.
you can Make ScreentextBox as Public in Declaring class and access it in Another class like
class Otherclass
{
public void ShowTextBox()
{
Class1.ScreenTextBox.Visible =true;
}
}
You could define the ShowTextBox method in a partial class So you still have the access to the control and also tidy your code.
Add method for showing TextBox in your form:
public partial class Form1 : Form
{
public void ShowTextBox()
{
screentextBox.Visible = true;
}
}
and then pass your From1 to other forms and call this method from there.
Class OtherClass
{
public static void method(TextBox[] items)
{
foreach(item in items)
{
(item as TextBox).Visible = true;
}
}
}
to call this method from ur Form1.cs class--->
OtherClass.method( new TextBox[] { TxtBox1, TxtBox2, TxtBox3 } );
If you want to access the controls of Form1.cs from another class try this way
class Otherclass
{
Form1 f1 = new Form1();
f1.Controls["screentextBox"].Visible = true;
}
I would do it like this (example from John Willemse):
class OtherClass
{
public TextBox ShowTextBox(TextBox target)
{
target.Visible = true;
return target;
}
}
Yet another approach to this old problem: I've found that the old way is an easy way to make accessible controls (including all their properties and methods), and perhaps other variables, from any class within the project. This old way consists of creating an ad hoc class from scratch.
Note A: about the old way: I know, I know, global variables are evil. But, for many people coming here looking for a fast/flexible/suites-most-cases solution, this may be a valid answer and I have not seen it posted. Another thing: this solution is what I am actually using as the answer for what I came to this page looking for.
1st step: The new class file from scratch is below.
namespace YourProjectNamespace
{
public class dataGlobal
{
public System.Windows.Forms.TextBox txtConsole = null;
// Place here some other things you might want to use globally, e.g.:
public int auxInteger;
public string auxMessage;
public bool auxBinary;
// etc.
}
}
Note B: The class is not static nor has static members, which allows to create several instances in case it is needed. In my case I do take advantage of this feature. But, as a matter of fact, you may consider making this class' TextBox a public static field so that -once initialized- it is always the same throughout the application.
2nd step: Then you're able to initialize it in your Main Form:
namespace YourProjectNamespace
{
public partial class Form1 : Form
{
// Declare
public static dataGlobal dataMain = new dataGlobal();
public Form1()
{
InitializeComponent();
// Initialize
dataMain.txtConsole = textBox1;
}
// Your own Form1 code goes on...
}
}
3rd step: And from your other class (or form), the call to any property/method of Form1's textBox1:
namespace YourProjectNamespace
{
class SomeOtherClass
{
// Declare and Assign
dataGlobal dataLocal = Form1.dataMain;
public void SomethingToDo()
{
dataLocal.txtConsole.Visible = true;
dataLocal.txtConsole.Text = "Typing some text into Form1's TextBox1" + "\r\n";
dataLocal.txtConsole.AppendText("Adding text to Form1's TextBox1" + "\r\n");
string retrieveTextBoxValue = dataLocal.txtConsole.Text;
// Your own code continues...
}
}
}
[EDIT]:
A simpler approach, specifically for the TextBox visibility throughout classes, I have not seen in other answers:
1st step: Declare and initialize an auxiliary TextBox object in your Main Form:
namespace YourProjectNamespace
{
public partial class Form1 : Form
{
// Declare
public static TextBox txtConsole;
public Form1()
{
InitializeComponent();
// Initialize
txtConsole = textBox1;
}
// Your own Form1 code goes on...
}
}
2nd step: And from your other class (or form), the call to any property/method of Form1's textBox1:
namespace YourProjectNamespace
{
class SomeOtherClass
{
public void SomethingToDo()
{
Form1.txtConsole.Visible = true;
Form1.txtConsole.Text = "Typing some text into Form1's TextBox1" + "\r\n";
Form1.txtConsole.AppendText("Adding text to Form1's TextBox1" + "\r\n");
string retrieveTextBoxValue = Form1.txtConsole.Text;
// Your own code continues...
}
}
}
Comment to the [Edit]: I have noticed that many questions simply cannot be solved by the usual recommendation: "instead, make public properties on your form to get/set the values you are interested in". Sometimes there would be several properties/methods to implement... But, then again, I know... best practices should prevail :)
This should be quite simple really - not sure what the problem is.
I have a C# Class (Public.cs) and a windows form (Form1.cs). Through a function in Public.cs, I want to get the value of a control on Form1 (without having to use object parameters).
// This code appears in Public.cs
public string MyFunction(int num_val)
{
if (chk_num.checked == true)
{
// Something here...
}
}
The issue is that my class cannot find the control on my form. Is there some way that I must reference it in C#?
Thank you.
I would strongly suggest exposing the Checked property via a specific property on Form1 (perhaps with a more meaningful name). This will help to hide the implementation details (i.e. control structure) of the Form1 from it's caller and instead expose only the logic that is required for other consumers to do their job
For example:
public bool IsNumberRequested
{
get { return chk_num.Checked; }
}
Or alternatively, if you still really want to access the control directly, from the designer you can select the control and change it's Modifier property to public (or something else) enabling you to access the control object using the code you originally wrote above.
EDIT: (Response based on comment)
Public.cs will still need a reference to Form1 and then will call the IsNumberRequested property of that object.
// Public.cs
public class Public
{
private Form1 _ui;
public Public(Form1 ui) { _ui = ui };
public string MyFunction(int num_val)
{
if (_ui.IsNumberRequested)
{
// Stuff
}
// Else, default Stuff
}
}
Alternatively, you could pass the form as a parameter to the MyFunction too rather than using it as an instance variable.
I would have the set up the other way around
public class Public
{
public bool CheckNumber {get;set;}
public string MyFunction(int val)
{
if(CheckNumber)
{
//do that thing
}
return ...
}
}
public partial class Form1 : Form
{
Public myinstance = new Public();
public Form1()
{
InitializeComponent();
}
private void CheckBoxChanged(object sender, EventArgs e)
{
myinstance.CheckNumber = chk_num.checked;
}
}
You'll need to assign CheckBoxChanged to the OnChanged event handler for your check box (which I'm assuming is chk_num.
This way your class Public doesn't rely on a form, which it shouldn't.
As Reddog says, use better names, although I half suspect you've just given example names in your question.
hey guys, i have 3 winForms named carForm,parForm and updateForm, so there's updateForm.show() method in both carForm n parForm, while m in updateForm i want to know which class/form has called updateForm, so that i can update the respected class db. Currently i'm setting up a public global variable to verify that which form is calling updateForm..but i was thinkin' is there's another way to do this, i guess Reflection can solve this issue, but i'm not able to solve it, here's my code
///carForm
public class carForm:Form
{
Program.globalvariable="CAR"; //global variable
UpdateFrom updateForm=new UpdateForm();
updateForm.Show();
}
///parForm
public class parForm:Form
{
Program.globalvariable="PAR";
UpdateFrom updateForm=new UpdateForm
updateForm.Show();
}
///updateForm
public class updateForm:Form
{
if(Program.globalvariable=="CAR")
///code for update CAR db table
else if(Program.globalvariable=="PAR")
///code for update PAR db table
Type obj = GetType(); //This is what i was tryin' using Reflection but giving error
}
so if i get the calling Class/Objects info, i can update respected DB table,
can ne1 know hw to do this with Reflection,
Put the argument in a constructor of updateForm
///carForm
public class carForm:Form
{
UpdateFrom updateForm=new UpdateForm("CAR");
updateForm.Show();
}
///parForm
public class parForm:Form
{
UpdateFrom updateForm=new UpdateForm("PAR");
updateForm.Show();
}
///updateForm
public class updateForm:Form
{
private readonly string _key;
public updateForm(string key)
{
_key = key;
}
public void SomeMethod()
{
// check for _key here.
}
}
Edit:
If you want to have the actual type you can pass it directly, no need for reflection.
///carForm
public class carForm:Form
{
UpdateFrom updateForm=new UpdateForm(this.GetType());
updateForm.Show();
}
///parForm
public class parForm:Form
{
UpdateFrom updateForm=new UpdateForm(this.GetType());
updateForm.Show();
}
///updateForm
public class updateForm:Form
{
private readonly Type _type;
public updateForm(Type type)
{
_type = type;
}
public void SomeMethod()
{
// check for _type here.
}
}
Edit 2:
But in general, passing the type like this smells like bad code. Your control flow will probably end up like a bowl of spaghetti.
If you want the updateForm to update some values on the other forms you should
Send all relevant information about what questions/titles/etc to show in the updateForm in the constructor of the updateForm.
In the updateForm, save relevant "answers" to public properties of updateForm
Set DialogResult in updateForm to OK or Cancel depending on how you exit updatForm
Call updateForm like this: if (updateForm.ShowDialog == DialogResult.OK) {// read all properties from updateForm}
You'd probably have to look at the StackTrace class if you wanted to automatically get that kind of information. Not sure about the performance of using it though...