Checking To Make Sure My Object isn't Partially Initialized - c#

I'm creating a simple application that takes a URL and a String and create the code for a hyperlink.
Here is my HyperLink Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinkIt_
{
class HyperLink
{
private string url;
private string text;
public HyperLink()
{
}
public HyperLink(string url,string text)
{
this.Website = url;
this.Text = text;
}
public String Website
{
get
{
return url;
}
set
{
if (String.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Must have URL!");
}
this.url = value;
}
}
public String Text
{
get
{
return text;
}
set
{
if (String.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Must have Text!");
}
this.text = value;
}
}
public string addPoint()
{
return String.Format("<li>", url) + text + "</li>";
}
public override string ToString()
{
return String.Format("",url) + text + "" ;
}
}
}
Here is my Form Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace LinkIt_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
HyperLink link;
try
{
if (chkPoint.Checked)
{
txtDisplay.Text = "";
link = new HyperLink(txtLink.Text, txtText.Text);
txtDisplay.Text = link.addPoint();
}
else
{
txtDisplay.Text = "";
link = new HyperLink(txtLink.Text, txtText.Text);
txtDisplay.Text = link.ToString();
}
}
catch (ArgumentNullException msg)
{
MessageBox.Show(msg.Message);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Text = "";
txtLink.Text = "";
txtText.Text = "";
}
}
}
My Question:
How do I make sure that I don't create a partially initialized object?
If my code need correcting, Could someone help me ?

You could refactor your code to use properties with decreased accessor visibility.
This way the HyperLink objects can not be altered from outside the class (this is often a preferable attribute for data structures).
For example you could do something like this:
class HyperLink
{
public String Website{get; private set;}
public String Text {get; private set;}
public HyperLink(string url,string text)
{
if(string.isNullOrEmpty(url) || string.IsNullOrEmpty(text))
throw new ArgumentNullException("no partially intialized object allowed");
this.Website = url;
this.Text = text;
}
public string AddPoint()
{
return String.Format("<li>", url) + text + "</li>";
}
public override string ToString()
{
return String.Format("",url) + text + "" ;
}
}
Update to answer question in comments
Yes, it is perfectly reasonable to use the Getter/Setter from within the same object or class.
However, I advise to improve your usage of String.Format to the following:
String.Format("{1}",this.Link, this.Text);

Related

C# ApplyTheme method to work on all forms simultaneously

I'm trying to implement a theme changer to my app. So far I've done this:
BaseForm - has all the functions to be inherited from, it's a lengthy one so if required I'll post it here. What troubles I'm having is as follows:
MainForm has a button to open UserSettings where the user can change the theme. Problem is, I managed to get it down that the theme applies, but only for the UserSettings window, and I want it to apply to anything that is open (if there is anything else).
Edit: adding more code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Windows.Forms;
using IniParser;
using ME___Tooling_Designer_App.Properties;
namespace ME___Tooling_Designer_App.Configuration;
public partial class UserSettings : BaseForm
{
public UserSettings()
{
InitializeComponent();
ApplyTheme();
ReadConfiguration();
}
// this is where the theme should be applied upon close
private void CBoxTheme_DropDownClosed(object sender, EventArgs e)
{
var parser = new FileIniDataParser();
var data = parser.ReadFile(_filePathSettings);
if (cBoxTheme.SelectedIndex == 0)
{
data["User_Settings"]["Theme"] = "Dark";
parser.WriteFile(_filePathSettings, data);
GlobalTheme = Enumerators.Theme.Dark;
}
if (cBoxTheme.SelectedIndex == 1)
{
data["User_Settings"]["Theme"] = "Light";
parser.WriteFile(_filePathSettings, data);
GlobalTheme = Enumerators.Theme.Light;
}
ApplyTheme();
}
public override void ApplyThemeSpecific(ThemeSettings settings)
{
panel1.BackColor = settings.PrimaryColor;
label2.ForeColor = settings.PrimaryFontColor;
btnExit.BackColor = settings.PrimaryColor;
btnExit.ForeColor = settings.PrimaryFontColor;
groupBox1.ForeColor = settings.PrimaryFontColor;
groupBox2.ForeColor = settings.PrimaryFontColor;
panel2.BackColor = settings.SecondaryColor;
}
Edit: this is BaseForm code:
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
namespace ME___Tooling_Designer_App.Configuration;
public class BaseForm : Form
{
public static List<PrivateFontCollection> FontCollections;
public static Enumerators.Theme GlobalTheme { get; set; }
public void ApplyTheme()
{
var settings = new ThemeSettings();
if (GlobalTheme == Enumerators.Theme.Dark)
{
settings.PrimaryColor = Color.FromArgb(32, 30, 50);
settings.SecondaryColor = Color.FromArgb(32, 30, 45);
settings.TertiaryColor = Color.FromArgb(11, 7, 17);
settings.QuaternaryColor = Color.FromArgb(23, 21, 32);
settings.QuinaryColor = Color.FromArgb(35, 32, 39);
settings.SenaryColor = Color.LightGray;
settings.SeptenaryColor = Color.Gainsboro;
settings.PrimaryFontColor = Color.Gainsboro;
}
else if (GlobalTheme == Enumerators.Theme.Light)
{
settings.PrimaryColor = Color.LightGray;
settings.SecondaryColor = Color.GhostWhite;
settings.TertiaryColor = Color.Gainsboro;
settings.QuaternaryColor = Color.DarkGray;
settings.QuinaryColor = Color.Silver;
settings.SenaryColor = Color.Gray;
settings.SeptenaryColor = Color.Black;
settings.PrimaryFontColor = Color.Black;
}
ApplyThemeSpecific(settings);
}
public virtual void ApplyThemeSpecific(ThemeSettings settings)
{
}
}
public class Enumerators
{
public enum Theme
{
NotSet,
Light,
Dark
}
}
public class ThemeSettings
{
public Color PrimaryColor { get; set; }
public Color SecondaryColor { get; set; }
public Color TertiaryColor { get; set; }
public Color QuaternaryColor { get; set; }
public Color QuinaryColor { get; set; }
public Color SenaryColor { get; set; }
public Color SeptenaryColor { get; set; }
public Color PrimaryFontColor { get; set; }
}
this is my Program.cs:
using System;
using System.Windows.Forms;
using IniParser;
using ME___Tooling_Designer_App.Configuration;
using ME___Tooling_Designer_App.Forms;
namespace ME___Tooling_Designer_App
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
var parser = new FileIniDataParser();
var data = parser.ReadFile(Application.StartupPath + #"\" + "Config" + #"\" + "settings.ini");
var themeSetting = data["User_Settings"]["Theme"];
Application.EnableVisualStyles();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.SetCompatibleTextRenderingDefault(false);
if (themeSetting == "Light")
{
BaseForm.GlobalTheme = Enumerators.Theme.Light;
}
else if (themeSetting == "Dark")
{
BaseForm.GlobalTheme = Enumerators.Theme.Dark;
}
else
{
BaseForm.GlobalTheme = Enumerators.Theme.NotSet;
}
Application.Run(new Login());
}
}
}
tried doing it as MainForm.ApplyTheme, but that just returns to UserSettings nonetheless
Edit: adding snippets of MainForm:
namespace ME___Tooling_Designer_App.Forms;
public partial class MainForm : BaseForm
{
/// <summary>
/// Constructor
/// </summary>
public MainForm()
{
InitializeComponent();
ApplyTheme();
CreateDirectories();
CustomizeDesign();
InitializeDatFiles();
InitializeIniConfiguration();
ReadFont();
ReadComputer();
ReadSystem();
TestTrial();
DaysRemainColoring();
CompareComputerNameAndLicense();
lblUser.Text = Environment.UserName;
}
public override void ApplyThemeSpecific(ThemeSettings settings)
{
panelTopBar.BackColor = settings.PrimaryColor;
btnInfo.BackColor = settings.PrimaryColor;
btnMinimize.BackColor = settings.PrimaryColor;
btnExitTop.BackColor = settings.PrimaryColor;
panelCenter.BackColor = settings.SecondaryColor;
panelSideMenu.BackColor = settings.TertiaryColor;
panelSideMenuLogo.BackColor = settings.TertiaryColor;
btnMainMenu.BackColor = settings.TertiaryColor;
btnSettings.BackColor = settings.TertiaryColor;
btnSave.BackColor = settings.TertiaryColor;
btnLoad.BackColor = settings.TertiaryColor;
btnExit.BackColor = settings.TertiaryColor;
panelQuickView.BackColor = settings.QuaternaryColor;
panelMainMenu.BackColor = settings.QuinaryColor;
panelSettings.BackColor = settings.QuinaryColor;
btnNewProject.BackColor = settings.QuinaryColor;
btnExistingProject.BackColor = settings.QuinaryColor;
btnReadProject.BackColor = settings.QuinaryColor;
btnSearchProject.BackColor = settings.QuinaryColor;
btnUserSettings.BackColor = settings.QuinaryColor;
btnAppSettings.BackColor = settings.QuinaryColor;
}
The solution is to add a timer
Because your problem is to update all windows, you just need to add a timer control to each window.
Timer:
BaseForm:
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp4 {
public partial class BaseForm : Form {
public BaseForm () {
}
private static Image baseImage=null;
public static Image BaseImage {
get {
return baseImage;
}
set {
baseImage = value;
}
}
}
}
SettingsForm:
using System;
namespace WindowsFormsApp4 {
public partial class SettingsForm : BaseForm {
public SettingsForm () {
InitializeComponent();
}
private void button1_Click (object sender, EventArgs e) {
BaseImage = Resource.tiger;
}
private void button2_Click (object sender, EventArgs e) {
BaseImage = Resource.windows;
}
private void timer1_Tick (object sender, EventArgs e) {
this.BackgroundImage = BaseImage;
}
}
}
Form1:
using System;
namespace WindowsFormsApp4 {
public partial class Form1 : BaseForm {
public Form1 () {
InitializeComponent();
}
private void button1_Click (object sender, EventArgs e) {
SettingsForm settingsForm=new SettingsForm();
settingsForm.ShowDialog();
}
private void timer1_Tick_1 (object sender, EventArgs e) {
this.BackgroundImage = BaseImage;
}
}
}
Resource.resx:
OutPut:
You can change it according to your needs.
If you have any questions, please comment below, and I will continue to follow up.
Try this code on all forms of your project on Activated and Load events.
Such as, MainForm:
private void MainForm_Activated(object sender, EventArgs e)
{
ApplyTheme();
}
Update: Try following line on BaseForm, if it works, add override on all forms and change the color values of all elements:
public virtual void ApplyThemeSpecific(ThemeSettings settings)
{
Background = settings.PrimaryColor; //for example
}
Update 2: Add a timer on all forms that checks theme change, and when theme changes, it changes the visual. Or you can make a event when theme changes.

How do I set property to zero

I need to set a label to zero. It is showing 120. There is a button that will return the required hours for this program. It is a program that returns the required hours for students major. There are 3 forms. bladah bladah yadah yadah. asdfkashdfjkhasjkdhfjkasdjkfajkdjfkajksdfjkakjshdfkjakjsdfjkashdfakjsdf
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Computer_Science_Student
{
class CompSciStudent : Student
{
// Constants
private double MATH_HOURS = 20;
private double CS_HOURS = 40;
private double GEN_HOURS = 60;
// Fields
private string _academicTrack;
// Constructor
public CompSciStudent(string name, string id, string track)
: base(name, id)
{
_academicTrack = track;
}
// AcademicTrack property
public string AcademicTrack
{
get { return _academicTrack; }
set { _academicTrack = value; }
}
// RequiredHours property
public override double RequiredHours
{
get { return MATH_HOURS + CS_HOURS + GEN_HOURS; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Computer_Science_Student
{
abstract class Student
{
// Fields
private string _name;
private string _id;
// Constructor
public Student(string name, string id)
{
_name = name;
_id = id;
}
// Name property
public string Name
{
get { return _name; }
set { _name = value; }
}
// ID property
public string ID
{
get { return _id; }
set { _id = value; }
}
// RequiredHours property (abstract)
public abstract double RequiredHours
{
get;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Computer_Science_Student
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Variables to hold input
string name, id, track;
// Get the student's name and ID.
name = nameTextBox.Text;
id = idTextBox.Text;
// Get the student's academic track
if (infoSystemsRadioButton.Checked)
{
track = "Information Systems";
}
else
{
track = "Software Engineering";
}
// Create a CompSciStudent object.
CompSciStudent csStudent =
new CompSciStudent(name, id, track);
// Display the student's required hous.
requiredHoursLabel.Text =
csStudent.RequiredHours.ToString("n1");
}
private void ExitButton_Click(object sender, EventArgs e)
{
// Close the form
this.Close();
}
}
}
In your code class CompSciStudent has the following attributes and methods:
// Constants
private double MATH_HOURS = 20;
private double CS_HOURS = 40;
private double GEN_HOURS = 60;
public override double RequiredHours
{
get { return MATH_HOURS + CS_HOURS + GEN_HOURS; }
}
RequiredHours always returns sum of MATH_HOURS + CS_HOURS + GEN_HOURS, which equals 120.
Also as another person pointed out, those are not constants, they are variables. A constant would be:
const double MATH_HOURS = 20;
Here you're creating a new CompSciStudent object:
// Create a CompSciStudent object.
CompSciStudent csStudent = new CompSciStudent(name, id, track);
// Display the student's required hous.
requiredHoursLabel.Text = csStudent.RequiredHours.ToString("n1");
In your Form1_Load() method you're setting requiredHoursLabel.Text to csStudent.RequiredHours which is always 120 that's why you're seeing "120" in the text field.
The Form1_Load() method is going to be called after your form loads so it is typically used to initialize the form. So what you're doing right now is to initialize requiredHoursLabel.Text to 120.
If you have some other behavior in mind they you'll need to add something like another button besides "Close" like "OK" or "Save" or something to accept the input the user entered into the form.

How to add support of multiobject edits for PropertyGrid's custom property editor?

This is the simplest ever custom property editor that contains just a form with one more PropertyGrid:
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms.Design;
namespace PageControls
{
public partial class PropertyGridEditor : Form
{
public object ObjectToEdit;
public delegate void PropertyValueChangedEventHandler(object sender, PropertyValueChangedEventArgs e);
public static event PropertyValueChangedEventHandler PropertyValueChangedStatic;
public event EventHandler<PropertyValueChangedEventArgs> PropertyValueChanged;
public PropertyGridEditor(object obj_to_edit)
{
InitializeComponent();
this.ObjectToEdit = obj_to_edit;
}
private void PropertyGridEditor_Load(object sender, EventArgs e)
{
this.prop_grid.SelectedObject = ObjectToEdit;
}
private void PropertyGridEditor_FormClosed(object sender, FormClosedEventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void prop_grid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
var evt = PropertyGridEditor.PropertyValueChangedStatic;
if (evt != null)
evt(s, e);
var evt2 = this.PropertyValueChanged;
if (evt2 != null)
evt2(s, e);
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class InnerPropertyGridEditor : UITypeEditor
{
public InnerPropertyGridEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
// Indicates that this editor can display a Form-based interface.
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
// Attempts to obtain an IWindowsFormsEditorService.
IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (edSvc == null)
return null;
using (PropertyGridEditor form = new PropertyGridEditor(value)) //when two or more properties were selected the value is null :/
if (edSvc.ShowDialog(form) == DialogResult.OK)
return form.ObjectToEdit;
return value; // If OK was not pressed, return the original value
}
}
}
So, now I have a class:
class Test
{
public bool Prop1 { get; set; }
public bool Prop2 { get; set; }
}
And I have main class that has this Test class as property.
class MainClass
{
[Editor(typeof(InnerPropertyGridEditor), typeof(UITypeEditor))]
public Test test_prop { get; set; }
...
}
My main PropertyEditor supports multi selected objects.
So, I can select two or more MainClasses to edit their properties.
The problem is - when I do that and tries to edit test_prop InnerPropertyGridEditor appears empty, because of passed value is null.
Actually, I hoped it to be at least object[] so I can implement something.
Ok, in case if no one will ever answer this I will show the hacky solution I made:
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using System.Reflection;
namespace PageControls
{
public partial class PropertyGridEditor : Form
{
public object Result;
public static event EventHandler<PropertyValueChangedEventArgs> PropertyValueChangedStatic;
public event EventHandler<PropertyValueChangedEventArgs> PropertyValueChanged;
public PropertyGridEditor(object[] obj_to_edit)
{
InitializeComponent();
this.prop_grid.SelectedObjects = obj_to_edit;
this.Result = obj_to_edit[0];
}
private void PropertyGridEditor_Load(object sender, EventArgs e)
{
}
private void PropertyGridEditor_FormClosed(object sender, FormClosedEventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void prop_grid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
var evt = PropertyGridEditor.PropertyValueChangedStatic;
if (evt != null)
evt(s, e);
var evt2 = this.PropertyValueChanged;
if (evt2 != null)
evt2(s, e);
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class InnerPropertyGridEditor : UITypeEditor
{
public InnerPropertyGridEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
// Indicates that this editor can display a Form-based interface.
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
// Attempts to obtain an IWindowsFormsEditorService.
IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (edSvc == null)
return null;
object[] values = new object[context.Instance is object[] ? ((object[])context.Instance).Length : 1];
if (context.Instance is object[])
for (int i = 0; i < ((object[])context.Instance).Length; i++)
{
PropertyInfo pi = ((object[])context.Instance)[i].GetType().GetProperty(context.PropertyDescriptor.Name);
values[i] = pi != null ? pi.GetValue(((object[])context.Instance)[i], null) : null;
}
else
values[0] = value;
using (PropertyGridEditor form = new PropertyGridEditor(values))
if (edSvc.ShowDialog(form) == DialogResult.OK)
return form.Result;
return value; // If OK was not pressed, return the original value
}
}
}

Highlighting and editing Grids

I currently have a gridview that is populated via database through a c# method.
I wanted to know if there was a way to select the row when clicked anywhere on the row and not use the select button altogether. And then have the information from that row be sent back and populate another area on the webpage.
Is there a grid better than gridview for this? Should I outsource to jQuery? Or is gridview all I should need?
what you need to do is develop a row-clickable GridView. Best bet is to follow the instructions in the link. If your okay with VB, you can go along that route. A user has also converted it into C#, its in the comments section. Ill include it incase you dont see it.
Heres a link I have saved: http://aspadvice.com/blogs/joteke/archive/2006/01/07/14576.aspx
using System;
using System.ComponentModel;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomGridView
{
/// <summary>
/// Summary description for ClickableGridView
/// </summary>
public class ClickableGridView : GridView
{
public string RowCssClass
{
get
{
string rowClass = (string)ViewState["rowClass"];
if (!string.IsNullOrEmpty(rowClass))
return rowClass;
else
return string.Empty;
}
set
{
ViewState["rowClass"] = value;
}
}
public string HoverRowCssClass
{
get
{
string hoverRowClass = (string)ViewState["hoverRowClass"];
if (!string.IsNullOrEmpty(hoverRowClass))
return hoverRowClass;
else
return string.Empty;
}
set
{
ViewState["hoverRowClass"] = value;
}
}
private static readonly object RowClickedEventKey = new object();
public event GridViewRowClicked RowClicked;
protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
{
if (RowClicked != null)
RowClicked(this, e);
}
protected override void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith("rc"))
{
int index = Int32.Parse(eventArgument.Substring(2));
GridViewRowClickedEventArgs args = new GridViewRowClickedEventArgs(Rows[index]);
OnRowClicked(args);
}
else
base.RaisePostBackEvent(eventArgument);
}
protected override void PrepareControlHierarchy()
{
base.PrepareControlHierarchy();
for (int i = 0; i < Rows.Count; i++)
{
string argsData = "rc" + Rows[i].RowIndex.ToString();
Rows[i].Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(this, argsData));
if (RowCssClass != string.Empty)
Rows[i].Attributes.Add("onmouseout", "this.className='" + RowCssClass + "';");
if (HoverRowCssClass != string.Empty)
Rows[i].Attributes.Add("onmouseover", "this.className='" + HoverRowCssClass + "';");
}
}
}
public class GridViewRowClickedEventArgs : EventArgs
{
private GridViewRow _row;
public GridViewRowClickedEventArgs(GridViewRow aRow)
: base()
{
_row = aRow;
}
public GridViewRow Row
{
get
{ return _row; }
}
}
public delegate void GridViewRowClicked(object sender, GridViewRowClickedEventArgs args);
}

C# user control crashing VS11

I'm finding myself coding C3 for the first time, and using Visual Studio for the first time in a looong time.
I'm creating a user control that allows for picking a file/folder etc, for making that kindof control easier to implement in the future. However whenever I drag the control unto any form, Visual Studio crashes instantly. I have tried rebuilding the entire solution several times.
The error seems to only happen when creating public variables in the control...
Does anyone know how to get around this?
Code is work in progress.... ;)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BackupReport.tools
{
public partial class pathchooser : UserControl
{
#region "Datatypes"
public enum DLG { Folder, FileSave, FileOpen };
#endregion
#region "public properties"
public DLG Dtype
{
get
{
return this.Dtype;
}
set
{
this.Dtype = value;
}
}
public string labelText
{
get
{
return this.labelText;
}
set
{
this.labelText = value;
label1.Text = this.labelText;
}
}
#endregion
#region "Constructor"
public pathchooser()
{
InitializeComponent();
this.Dtype = DLG.Folder;
this.labelText = "Source:";
label1.Text = this.labelText;
}
#endregion
private void browse_button_Click(object sender, EventArgs e)
{
switch (this.Dtype)
{
case DLG.Folder:
if (fbd.ShowDialog() == DialogResult.OK)
{
path_textbox.Text = fbd.SelectedPath;
}
break;
case DLG.FileSave:
break;
case DLG.FileOpen:
break;
default:
break;
}
}
}
}
Any help would be appreciated.
also I'm not sure it matters, but I'm using VS11 beta.
//Martin
public DLG Dtype
{
get
{
return this.Dtype;
}
set
{
this.Dtype = value;
}
}
You have a property referring to itself, and thus calling its own getter and setter inside (respectively) the getter and setter. Something more appropriate would either be to either have empty accessors:
public DLG DType{get; set;}
or to have accessors referring to private variables:
private DLG dtype;
public DLG Dtype
{
get
{
return this.dtype;
}
set
{
this.dtype = value;
}
}
I think your properties are causing a StackOverflowException because the getters and setters invoke themselves in an endless loop (Dtype -> Dtype -> Dtype ...).
Try this code instead:
private string labelText;
public DLG Dtype { get; set; }
public string LabelText
{
get { return this.labelText; }
set
{
this.labelText = value;
label1.Text = value;
}
}

Categories

Resources