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();
}
Related
I have a code behind that has two classes within the same namespace. I'd like to reference the first classes public variables from the second class in the namespace. I know I could obviously pass the variables, but I'd like to know if there is a way to reference them.
namespace CADE.results
{
public partial class benchmark : BasePage
{
public string numAnswers = ""; <-- like to reference this from GetScore()
protected void Page_Load(object sender, EventArgs e)
{
BenchmarkAdd bma = new BenchmarkAdd();
bma.GetScore();
}
}
public class BenchmarkAdd
{
public BenchmarkAdd()
{
}
public void GetScore()
{
benchmark.numAnswers++; <-- would like to reference public var here
}
}
}
I thought just benchmark.numAnswers would work but it doesn't. Is it possible to reference numAnswers from the BenchmarkAdd class?
I'd like to reference the first classes public variables from the second class in the namespace.
Well numAnswers is an instance variable, so GetScore() isn't going to know which instance to update.
The only way this can be done (without passing your Page instance, or passing numAnswers using ref) is to make numAnswers static:
public static string numAnswers = "";
Which you could then update in GetScore():
public void GetScore()
{
CADE.results.benchmark.numAnswers++;
}
However, the effect of making this static is that each benchmark instance no longer has it's own numAnswers field; there would be only one copy of the field which would instead belong to the type itself.
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
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 :)
I have a method in my Mainwindow, i want to call this method in an other usercontrol.
I dont use a static method because my MainWindow is not Static, and I can't make it static.
So I figured out to use this, but I dont know what comes behind the AS and I dont know if I can put a method is VAR?
I also can't make another MainWindow instance because that gives me a Stackoverflow exception.
How can I solve this?
var myMethode= mainWindow.FindName("MyMethode") as (should be a methode);
if (myMethode!= null)
{
//My code
}
You can define a static method on a class that is not static.
For example:
static void Main()
{
Foo foo = new Foo();
Foo.DoSomething();
foo.DoSomethingElse();
}
public class Foo
{
public static void DoSomething()
{
Console.WriteLine("DoSomething");
}
public void DoSomethingElse()
{
Console.WriteLine("DoSomethingElse");
}
}
But wouldn't it be a better solution to pass the MainWindow as a parameter into the User Control? So the user controls knows to which window it belongs and can access a function on it? (even better to declare an interface for this and pas the interface around).
This would look like:
public interface IWindow
{
string SomeWindowActivity();
}
public class MyUserControl
{
public IWindow Window { get; set; }
public void SomeActionOnUserControl()
{
string data = Window.SomeWindowActivity();
}
}
public class MainWindow : IWindow
{
MyUserControl MyUserControl { get; set; }
public MainWindow()
{
// Link the UserControl to the Window it's one. This can be done trough the
// constructor or a property
MyUserControl.Window = this;
}
public string SomeWindowActivity()
{
// Some code...
return "result";
}
}
Try this
((MyMainWindow)Application.Current.MainWindow).Method()
You don't need to make MainWindow singleton in your case, you have access to it from Application.Current singleton
Application.Current.MainWindow
Hope this helps
Short unswer: you can't. You want to call a instance method, you need to have an instance.
The fact that MainWindow is not static does not prevent you from defining static methods in it, as long as those methods do not use other instance members, so if it a helper method, you can define it static and call from other place, it might a good idea to refactor it out of MainWindow class then.
If it's a nonstatic method, you claim you don't want to create second instance of MainWindow, why not call it on first instance then, by passing it to your control?
Also, if creating another instance of MainWindow gives you stackoverflow, maybe it's because you just did some recurrent call with this method, and it can be fixed?
Please excuse my ignorance, I am transitioning from VB6 to C# (very steep learning curve). I have googled this to death and I am not able to figure this out. I instantiated a Class on my main form:
namespace App1_Name
{
public partial class Form1 : Form
{
public cConfig Config = new cConfig();
}
}
In my Config Class I am instantiating two other classes:
namespace App1_Name
{
class cConfig
{
//Properties
public cApplication Application = new cApplication();
}
}
In my cApplications Class I have the following:
namespace App1_Name
{
class cApplication
{
//Properties
public string ApplicationName { get { return "App Name"; } }
}
}
So in another class I am looking to use the class I instantiated on Form1 as so:
namespace App1_Name
{
class cXML
{
public void Method1()
{
Console.WriteLine(Config.Application.ApplicationName);)
}
}
}
But I am getting an error that states "Config" doesn't exist in the current context, what am I doing wrong here?
Don't you miss instance of Form1?
Form1 form = new Form1();
Console.WriteLine(form.Config.Application.ApplicationName);
because you are working with properties... not static classes and static methods.
I think you want this:
Console.WriteLine(Form1.Config.Application.ApplicationName);
EDIT: Dampe is correct; you need an instance of Form1, since Config is not a static member of the class. Please refer to his answer.
All of the above, or a one-liner:
Console.WriteLine(new Form1().Config.Application.ApplicationName);
Ok, in order to get my original code to work I made the cApplication Static. This is because I was instantiating the cXML in Form1's Form_Load event so the above solutions just created an endless loop.
What I did to resolve the issue was to pass the Config Class as a reference to the cXML class as follows:
namespace App1_Name
{
public partial class Form1 : Form
{
public cConfig Config = new cConfig();
}
private void Form1_Load(object sender, EventArgs e)
{
cXML XML = new cXML();
XML.Config = Config; //Passing the Config Class by Reference to cXML
}
}
In the cXML class I am doing the following:
namespace App1_Name
{
class cXML
{
public cConfig Config;
public string AppName
{
Console.WriteLine(Config.Application.AppName);
}
}
}
This does exactly what I originally set out to do. My new question is is this an acceptable way of doing this?