asp.net - Access public class in Masterpage from child page - c#

I'm trying to access a public class in my MasterPage code file from a child page but cannot get it working. I've tried to use the same method as accessing a public int as follows but the child page doesn't recognise any of the class items.
MasterPage.cs
private int _Section;
public int Section
{
get{return _Section;}
set{_Section = value;}
}
public class HeaderPanel
{
private bool _Visible = true;
public bool Visible
{
get { return _Visible; }
set { _Visible = value; }
}
private string _Theme;
public string Theme
{
get { return _Theme; }
set { _Theme = value; }
}
public HeaderPanel(bool Visible, string Theme)
{
this.Visible = Visible;
this.Theme = Theme;
}
}
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Master.Section = 1; // This works
Master.HeaderPanel.Visible = true; // This doesn't work
Master.HeaderPanel.Theme = "Dark"; // This doesn't work
}
The error message I get is:
'HeaderPanel': cannot reference a type through an expression

Master.Section = 1;
This works because Master is a property on Default and that property is an instance of MasterPage. You are simply setting the Section value on that instance.
Master.HeaderPanel.Visible = true;
This doesn't work because, while Master is still the same instance, HeaderPanel is a type and not an instance of anything. So you're trying to set Visible statically on that type.
If you meant for it to be static, make it static:
private static bool _Visible = true;
public static bool Visible
{
get { return _Visible; }
set { _Visible = value; }
}
And access it via the type and not the instance:
MasterPage.HeaderPanel.Visible = true;
If, on the other hand (and possibly more likely?), you did not mean for it to be static, then you need an instance of the HeaderPanel type on a MasterPage instance. So in MasterPage you'd create a property for that:
private HeaderPanel _header = new HeaderPanel();
public HeaderPanel Header
{
get { return _header; }
set { _header = value; }
}
Then you could access it through that property:
Master.Header.Visible = true;

private int _Section;
public int Section
{
get{return _Section;}
set{_Section = value;}
}
//define your header panel as property
public HeaderPanel Header {Get;Set;}
then you can use it as below
protected void Page_Load(object sender, EventArgs e)
{
Master.Section = 1; // This works
Master.Header.Visible = true;
Master.Header.Theme = "Dark";
}

Related

Reseting label back to design-time .Text value

I have a bunch of labels that I set their value in the designer and later during runtime update them, but after using them, I want to set them back to their default value. My intent with this is to reduce the amount of large code to help make it easier to read.
random example like, setting in the designer of lbl_fruit Text = no fruits available currently then
*code*
lbl_fruits.Text = "banana";
*code*
lbl_fruits.ResetText(); // I want something like this
lbl_fruits.Text = "no fruits available currently"; // Instead of this
The .ResetText(); doesn't work for this as the label text gets cleaned instead of returning to "no fruits available currently"
My current solution is making a custom label control.
public class ExLabel : Label
{
private string defaultValue = "";
public string DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; this.Invalidate(); }
}
protected override void OnControlAdded(ControlEventArgs e)
{
defaultValue = this.Text;
MessageBox.Show("This code is being run");
base.OnControlAdded(e);
}
public void ResetValue()
{
this.Text = defaultValue;
}
}
This code currently solves my problem if I use the custom propriety I made, but for me the ideal solution would be to have the design-time text value as the default value and not an extra propriety I made. OnControlAdded() does not get executed, OnPaint() runs again when lbl_fruits.Text = "banana"; happens.
So the question is: Which event I can override so the code gets executed as soon as the label is loaded but doesn't run twice. And also, is there a simpler way of approaching this?
In the end the solution I used was this:
public class ExLabel : Label
{
private string defaultValue = "";
public string DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; this.Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
if(defaultValue == "" && !this.Text.Contains("exLabel"))
{
defaultValue = this.Text;
}
base.OnPaint(e);
}
public void ResetValue()
{
this.Text = defaultValue;
}
}
public class ExLabel : Label
{
private string defaultValue = "";
public string DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; this.Invalidate(); }
}
protected override void OnControlAdded(ControlEventArgs e)
{
defaultValue = this.Text;
MessageBox.Show("This code is being run");
base.OnControlAdded(e);
}
public void ResetValue()
{
this.Text = defaultValue;
}
}

How to set set and get for Textbox control?

I want to get value of TextBox in Form1, to another class.
I try to make a set and get, but I can't do this, because VS shows me error about ambiguity in code.
public partial class Form1 : Form
{
private TextBox _textBox1;
public Form1()
{
this._textBox1 = textBox1;
InitializeComponent();
}
public string _textBox1
{
get { return _textBox1.Text; }
set { _textBox1.Text = value; }
}
}
How to make this correct? My control is private.
You have one field and one property in you class with the same name, change the name of the property, for instance to
public string FormTextBox1
{
get { return _textBox1.Text; }
set { _textBox1.Text = value; }
}
as naming standard the public properties must be Pascal Case notation
Capitalization Conventions
You can pass textBox1.Text to a variable, and make a getter/setter for it.
Like this:
public class A : Form1
{
// assuming it's a string. If it's not, change the type
// for the getter method below accordingly
private string textBoxValue;
// at some point, you'll have to make this line below:
textBoxValue = textBox1.Value;
public string GetTextBoxValue()
{
return textBoxValue;
}
}
public class B
{
A aReference = new A();
// you can get the value you want by doing
// aReference.GetTextBoxValue();
}
public void yourFormLoadMethod()
{
//this instantiates a new object of your class
nameOfYourClass newYourObject = new nameOfYourClass(//put any params you need here);
txtNameOfYourTextBox.DataBindings.Add("Enabled", newLTDObjectBenInt, "YourTextBoxEnabled", true, DataSourceUpdateMode.OnPropertyChanged);
txtNameOfYourTextBox.DataBindings.Add("Value", newLTDObjectBenInt, "YourTextBoxEntered", true, DataSourceUpdateMode.OnPropertyChanged);
txtNameOfYourTextBox.DataBindings.Add("Visible", newLTDObjectBenInt, "YourTextBoxVisible", true, DataSourceUpdateMode.OnPropertyChanged);
}
public class nameOfYourClass
{
//constructor
public nameOfYourClass(//same params here from the Load method)
{
//place any logic that you need here to load your class properly
//this sets default values for Enable, Visible and the text
//you use these fields to manipulate your field as you wish
yourTextBoxVisible = true;
yourTextBoxEnabled = true;
yourTextBoxEntered = "this is the default text in my textbox";
}
private bool yourTextBoxEnabled;
public bool YourTextBoxEnabled
{
get
{
return yourTextBoxEnabled;
}
set
{
yourTextBoxEnabled = value;
}
}
private bool yourTextBoxVisible;
public bool YourTextBoxVisible
{
get
{
return yourTextBoxVisible;
}
set
{
yourTextBoxVisible = value;
}
}
private string yourTextBoxEntered;
public string YourTextBoxEntered
{
get
{
return yourTextBoxEntered;
}
set
{
yourTextBoxEntered = value;
}
}
}

C# swap in Designer

I have my Control.When I change the properties of the control. I get this:
this.myLabel1.BorderShadow = true;
this.myLabel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
And I need to get this:
this.myLabel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.myLabel1.BorderShadow = true;
How to do so is done automatically in Form.Desinger.cs ?
If you say Why?
private bool BorderShadow_ = false;
public bool BorderShadow
{
get
{
return BorderShadow_;
}
set
{
if (Border_Style_ == BorderStyle.FixedSingle)
{
BorderShadow_ = value;
}
else
{
throw new ArgumentOutOfRangeException("BorderShadow", "BorderShadow can be true if BorderStyle=FixedSingle");
}
}
}
You could look into the ISupportInitialize interface. It allows you to skip the validity check when initializing your controls. For example (adapted from one of my projects):
public class MyControl : Control, ISupportInitialize
{
private bool _created = true;
public void BeginInit()
{
_created = false;
}
public void EndInit()
{
_created = true;
//check all your properties here too
}
private bool BorderShadow_ = false;
public bool BorderShadow
{
get
{
return BorderShadow_;
}
set
{
BorderShadow_ = value;
if (_created && Border_Style_ != BorderStyle.FixedSingle)
throw new ArgumentOutOfRangeException();
}
}
}
If I remember correctly, the VS designer will automatically add calls to BeginInit and EndInit for you as well.
I think they will appears in the same order as they are defined. So you can override with new old setting:
public new BorderStyle BorderStyle
{
get {return base.BorderStyle;}
set {base.BorderStyle = value;}
}
and then declare your BorderShadow setting.
The designer will always order the properties alphabetically and this can't be changed.
The sense of a property is that it is side effect free and that it can be changed at any time in any order. This means that if you have multiple properties which representing some kind of complex state and not all combinations are making sense, this error should not be reported while switching the property itself.
So to accomplish these problems you have two possibilities:
Like #Andrew already mentioned implement ISupportInitialize and take care if you are within this state.
Within the property setter call a method that checks if all settings currently made are making sense and perform the desired action only in this case:
public class MyControl : Control
{
private bool _BorderShadow;
private BorderStyle _BorderStyle;
public bool BorderShadow
{
get { return _BorderShadow; }
set
{
if(_BorderShadow != value)
{
_BordeShadow = value;
ApplyBorderShadowIfNeeded();
}
}
}
public BorderStyle BorderStyle
{
get { return _BorderStyle; }
set
{
if(_BorderStyle != value)
{
_BorderStyle = value;
ApplyBorderShadowIfNeeded();
}
}
}
private void ApplyBorderShadowIfNeeded()
{
if(_BorderStyle == BorderStyle.FixedSingle
&& _BorderShadow)
{
// ToDo: Apply the shadow to the border.
}
}
}

Global Variables Return Unexpected Values

Well I was trying to assign global variable to read values from Check boxes and radio buttons but the values don't update when the selections are changed ! Where have I done wrong? Here's the code:
private void chkInMut_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.Mutate = 1;
}
private void chkShwCal_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.ShowCal = 1;
}
private void chkOutSol_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.OutCal = 1;
}
}
public static class GlobalVar
{
static int _MaxMin, _MutVal, _CalShow, _CalOut;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int Extrema
{
get
{
return _MaxMin;
}
set
{
_MaxMin = value;
}
}
public static int Mutate
{
get
{
return _MutVal;
}
set
{
_MutVal = value;
}
}
public static int ShowCal
{
get
{
return _CalShow;
}
set
{
_CalShow = value;
}
}
public static int OutCal
{
get
{
return _CalOut;
}
set
{
_CalOut = value;
}
}
}
when I try to print the numbers using this test satement, the values returned are unexpected :
maxMin = GlobalVar.Extrema;
calShow = GlobalVar.ShowCal;
calOut = GlobalVar.OutCal;
IsMutble = GlobalVar.Mutate;
txtOutput.Text += Convert.ToString("\nMaxima Minima"+maxMin+"\n"+"Show Cal : "+calShow+"\n"+"Output Cal :"+calOut+"\n"+"Mutate : "+IsMutble+"\n---------\n");
And when I check/un-check the boxes, the values are not updated as it should be. Where have I gone wrong?
Edit: Solved by adding Unchecked Parameter.
Probably you should write your event handlers like this
private void chkInMut_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.Mutate = (chkInMut.IsChecked ? 1 : 0);
}
and so on .....
I think the problem is with your public static properties. for example try this:
public static int Extrema
{
get
{
return GlobalVar._MaxMin;
}
set
{
GlobalVar._MaxMin = value;
}
}
and do the same for all other properties.
Edit:
and why are you using this stucture? You can set your static class to be like this:
public static class GlobalVar
{
public static int Extrema;
public static int Mutate;
public static int ShowCal;
}

Passing Properties Between Winforms When Using Singleton

Ok so I am trying to pass a boolean from my Login form to my Home form, normally this would be fine for me and I would just use a property. However I thought I could use a similar method this time but I am implementing the singleton factory on the forms.
Here is the Login code relevant to this:
The AdminAccess property gets set fine and I have checked the value is correct.
private bool adminAccess;
public bool AdminAccess
{
get { return adminAccess; }
private set { adminAccess = value; }
}
private void btnLogin_Click(object sender, EventArgs e)
{
//Some Code Does Stuff
OpenHome();
}
private void OpenHome()
{
HomeForm CreateHomeForm = HomeForm.HomeUI;
CreateHomeForm.StartupHome = this;
//Trying to set the property.
CreateHomeForm.AdminPermissions= this.AdminAccess;
CreateHomeForm.Show();
this.Hide();
}
Here is the relevant code from the Home form:
public HomeForm()
{
InitializeComponent();
//just to check what is in the property quickly
textBox1.Text = AdminPermissions.ToString();
}
private bool adminPermissions;
public bool AdminPermissions
{
private get { return adminPermissions; }
set { adminPermissions = value; }
}
public Form StartupHome
{
set;
get;
}
private static HomeForm homeUI;
public static HomeForm HomeUI
{
get
{
if (homeUI == null || homeUI.IsDisposed)
{
homeUI = new HomeForm();
}
return homeUI;
}
}
The value gets reset when the HomeUI if loop runs as a new instance of the form is created. I can't seem to think how to modify this to get a working solution. As you can tell I am fairly amateur so I'm just looking for a quick and clean solution to this :)
Thank you very much for your time in advance!
You assign the value in the constructor, BEFORE the AdminPermissions property is actually set. Change your code like this
public class HomeForm
{
public HomeForm()
{
InitializeComponent();
}
private bool adminPermissions;
public bool AdminPermissions
{
get { return adminPermissions; }
set {
adminPermissions = value;
textBox1.Text = value.ToString();
}
}
...
}
Try setting the textBox1.Text value in one of the Form events. Try Loaded first, then Activated. You're resetting it to false every time in your constructor!

Categories

Resources