how to make read only property available in my usercontrol - c#

i make user control from 3 text boxes but i don not how to declare read only property to it i tried many things but it do not work here is my code to make the control
i want to make it read only when needed like if i add checkbox i want if checkbox.check=true make my control readonly
public partial class dateIN : UserControl
{
Dates datess = new Dates();
public dateIN()
{
InitializeComponent();
}
private void dateIN_Leave(object sender, EventArgs e)
{
if (txtDay.Text != "" || txtMonth.Text != "" || txtYear.Text != "")
{
if (!datess.IsHijri(txtDay.Text.Trim() + "/" + txtMonth.Text.Trim() + "/" + txtYear.Text.Trim()))
{
txtDay.Focus();
}
}
}
public string Day
{
set { txtDay.Text = value; }
get { return txtDay.Text; }
}
public string Month
{
set { txtMonth.Text = value; }
get { return txtMonth.Text; }
}
public string Year
{
set { txtYear.Text = value; }
get { return txtYear.Text; }
}
need to know how to make read only property available here plz

just remove the set { } part of the property
Example:
public string Day
{
get { return txtDay.Text; }
}

I dont know the correlation of where your "txtDay", "txtMonth", "txtYear" come from, but you could do something like
public partial class dateIN : UserControl
{
...
...
private bool AllowEditing()
{ return SomeCondition when SHOULD be allowed...; }
public string Day
{
// only allow the set to apply the change if the "AllowEditing" condition
// is true, otherwise, ignore the attempt to assign.
set { if( AllowEditing() )
txtDay.Text = value; }
get { return txtDay.Text; }
}
// same concept for month and year too
}

so may you add some flag to your set when it is true then you set a value.
also you can work with textbox property called ReadOnly.

Related

C# how to get control focus when exception is thrown in middle layer class

I'm developing a Windows Forms app that has a lot of text and combo boxes which have to be entered manually. So there is a lot of checks if particular control is empty. I would like to get read of all validations in my UI and move them to the Middle Layer. This is great as UI is now validation free and exceptions are triggered as expected, but now I can't know which control causes exception to trigger. Well, I can, but not without intervention in my UI, which I obviously don't want, because this would make Middle layer validation unnecessary, as I could do it completely in UI. So, in short, what I would like to achieve is: if validation is triggered I would like to set focus to a control that causes exception, without focus hard setting in UI. Is this possible? Or if not, what would be the best solution? Any help appreciated.
I have created a simple example:
private void btnConfirm_Click(object sender, EventArgs e)
{
try
{
Customer.CustomerTN = txtCustomerTN.Text;
Customer.CustomerName = txtCustomerName.Text;
Customer.CustomerPhone = txtCustomerPhone.Text;
MessageBox.Show("Customer TN: " + Customer.CustomerTN +
Environment.NewLine +
"Customer Name: " + Customer.CustomerName +
Environment.NewLine +
"Customer Phone: " + Customer.CustomerPhone);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
//Middle Layer Class
public class Customer
{
private static string customerTN;
private static string customerName;
private static string customerPhone;
public static string CustomerTN
{
get
{
return customerTN;
}
set
{
if (value.Length == 0)
{
throw new Exception("Enter Customer TN...");
}
else
{
customerTN = value;
}
}
}
public static string CustomerName
{
get
{
return customerName;
}
set
{
if (value.Length == 0)
{
throw new Exception("Enter Customer Name...");
}
else
{
customerName = value;
}
}
}
public static string CustomerPhone
{
get
{
return customerPhone;
}
set
{
if (value.Length == 0)
{
throw new Exception("Enter Customer Phone...");
}
else
{
customerPhone = value;
}
}
}
}
You could create a hierarchy of Validation classes. Every Validation class would have a list of controls to validate. When the validation takes place, if the control doesn't complies with the rules, you can abort validation by showing up a message and giving focus to that control, e.g.:
public abstract class ControlValidator<T> where T : Control
{
protected List<T> ControlsToValidate;
public ControlValidator(IEnumerable<T> controls)
{
this.ControlsToValidate = new List<T>(controls);
}
public abstract bool ValidateControls();
}
Then, if you want a validator for text boxes you would create a validator like:
public class TextBoxValidator : ControlValidator<TextBox>
{
public TextBoxValidator(IEnumerable<TextBox> controls) : base(controls)
{}
public override bool ValidateControls()
{
foreach(TextBox tb in ControlsToValidate)
{
if (tb.Text == "") // This validates the text cannot be empty
{
MessageBox.Show("Text cannot be empty");
tb.Focus();
return false;
}
}
return True;
}
}
Then you would create a list of validators to store all the validators of your app:
List<ControlValidator> validators = ...
To validate all your controls you would do a foreach like:
foreach(var validator in validators)
{
if (!validator.ValidateControls())
break;
}
The foreach is interrupted once it finds out that at least one control wasn't successfully validated. Hope it helps.

Passing a true value to a boolean

I am trying to learn C# and I am up to an example that uses a boolean. For the life of me I cant figure out why the program isnt noticing that I am trying to pass a value of true to the boolean. Here is the code in the Form.cs:
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
HappyBirthday birthdayMessage = new HappyBirthday();
string returnedMessage;
birthdayMessage.PresentCount = 5;
birthdayMessage.MyProperty = "Adam";
birthdayMessage.hasParty = true;
returnedMessage = birthdayMessage.MyProperty;
MessageBox.Show(returnedMessage);
}
}
}
Here is the Class that I created:
class HappyBirthday
{
//====================
// CLASS VARIABLES
//====================
private int numberOfPresents;
private string birthdayMessage;
private bool birthdayParty;
//===========================
// DEFAULT CONSTRUCTOR
//===========================
public HappyBirthday()
{
numberOfPresents = 0;
//birthdayParty = false;
}
//===========================
// METHOD
//===========================
private string getMessage(string givenName)
{
string theMessage;
theMessage = "Happy Birthday " + givenName + "\n";
theMessage += "Number of presents = ";
theMessage += numberOfPresents.ToString() + "\n";
if (birthdayParty == true)
{
theMessage += "Hope you enjoy the party!";
}
else
{
theMessage += "No party = sorry!";
}
return theMessage;
}
//================================
// READ AND WRITE PROPERTY
//================================
public string MyProperty
{
get { return birthdayMessage; }
set { birthdayMessage = getMessage(value); }
}
//================================
// WRITE-ONLY PROPERTY
//================================
public int PresentCount
{
set { numberOfPresents = value; }
}
public bool hasParty
{
set { birthdayParty = value; }
}
}
Now I set the initial value to false (even though if my understanding is correct that should be the default value), but when I try to set it = true, the program does not recognize it. Am I supposed to pass a boolean differently then I would a string or int?
You're setting MyProperty before you're setting hasParty. getMessage() is not being called every time MyProperty is polled.
The way MyProperty works is confusing, because the set and get deal with different values (you set the name, and then get the whole message, which is confusing). I'd replace it with a GivenName property and then make the GetMessage() (or expose it as a read-only property Message) public.
Also, you can make your code much simpler by using auto-properties (you can use private gets to keep the write-only behavior, though in the real world write-only properties are very rare, and you should probably just make them public like the sets). And since the default int value is 0, you don't need to specify your default constructor. Here's how the code looks now:
class HappyBirthday
{
public string Message
{
get
{
string theMessage;
theMessage = "Happy Birthday " + GivenName + "\n";
theMessage += "Number of presents = ";
theMessage += PresentCount.ToString() + "\n";
if (HasParty)
{
theMessage += "Hope you enjoy the party!";
}
else
{
theMessage += "No party = sorry!";
}
return theMessage;
}
}
public string GivenName { private get; set; }
public int PresentCount { private get; set; }
public bool HasParty { private get; set; }
}

Retaining enum values in asp.net

I have an asp.net page, wherein i am using enums (with Properties defined in class file in app_code)
Now my problem is whenever page gets postbacks the value of the enum in property gets resetted to the first one
I even tried setting the property as static, but still that didn't helped. below is my enum and property declaration:
private static UrlType _type;
public static UrlType UrlPattern
{
get
{
HttpContext.Current.Response.Write("GET: " +_type + "<br>");
return _type;
}
set
{
_type = value;
HttpContext.Current.Response.Write("SET : " +_type + "<br>");
}
}
public int VanityId { get; set; }
public enum UrlType
{
ArticleOnly,
ArticleCategoryCombination,
Normal,
TechForum
}
and this is how i calls:
public void BindRewrite()
{
GrdRewrite.DataSource = objVanity.GetAllRewriteVanities(Vanity.UrlPattern);
GrdRewrite.DataBind();
if (Vanity.UrlPattern == Vanity.UrlType.ArticleCategoryCombination)
{
GrdRewrite.Columns[2].Visible = false;
GrdRewrite.Columns[3].Visible = GrdRewrite.Columns[5].Visible = GrdRewrite.Columns[6].Visible = true;
}
else if (Vanity.UrlPattern == Vanity.UrlType.ArticleOnly)
{
GrdRewrite.Columns[5].Visible = true;
GrdRewrite.Columns[2].Visible = GrdRewrite.Columns[3].Visible = GrdRewrite.Columns[6].Visible = false;
}
else if (Vanity.UrlPattern == Vanity.UrlType.Normal)
{
GrdRewrite.Columns[2].Visible = true;
GrdRewrite.Columns[3].Visible = GrdRewrite.Columns[5].Visible = GrdRewrite.Columns[6].Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
pnlAdmin.Visible = (objVanity.UserName == "host");
if (objVanity.UserName == "host")
Enable();
else
FieldsOpenForEditors(objVanity.SiteSupportUrlFormat);
if (!IsPostBack)
{
Vanity.GenerateListFromEnums(drpAdminUrlType);
if (objVanity.UserName == "host")
Vanity.UrlPattern = Vanity.UrlType.ArticleOnly;
else
Vanity.UrlPattern = objVanity.SiteSupportUrlFormat;
BindRewrite();
}
}
can anyone tell me how to retain the value of the enum across postbacks
i think viewstate could be option, but don't have any clue about how to store the enum value and restore the string value casted in enum.
If you want to persist a value between post back, you need to store it in Session, Cache or ViewState.
In your case, ViewState could be a prefer choice.
public UrlType UrlPattern
{
get
{
if (ViewState["UrlPattern"] != null)
return (UrlType)Enum.Parse(typeof(UrlType), ViewState["UrlPattern"].ToString());
return UrlType.Normal; // Default value
}
set
{
ViewState["UrlPattern"] = value;
}
}

Unable to edit values in a DataGridView (using BindingList)

It seems that, due to an unknown cause, I am now unable to edit anything in my DataGridView. The DGV's ReadOnly property value is false, and all columns except for one all have the ReadOnly property set to false as well.
I'm beginning to think that it may be due to a special value I tried adding to one of my classes, one that I only wanted to be modified within the class, but still read only to the public. I don't think that value is messing with anything else, but none the less, here is the relevant portion of my code:
private void loaderWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
loadingBar.Value = e.ProgressPercentage;
if (e.UserState != null)
{
savefiles.Add((SaveFile)e.UserState);
}
}
Where savefiles is a BindingList, and where SaveFile is my class:
public class SaveFile
{
private string d_directory;
private int d_weirdnumber;
private bool d_isautosave;
private string d_fullname;
private string d_datatype;
private string d_owner;
private bool d_isquicksave;
private string d_title;
private string d_gametime;
public SaveFile() { }
public SaveFile(string directory, int weirdnumber, bool isautosave, string fullname, string datatype, string owner, bool isquicksave, string title)
{
d_directory = directory;
d_weirdnumber = weirdnumber;
d_isautosave = isautosave;
d_fullname = fullname;
d_datatype = datatype;
d_owner = owner;
d_isquicksave = isquicksave;
d_title = title;
}
public string Gametime
{
get { return d_gametime; }
}
public string Datatype
{
get { return d_datatype; }
set { d_datatype = value; }
}
public string Title
{
get { return d_title; }
set { d_title = value; }
}
public bool IsQuickSave
{
get { return d_isquicksave; }
set { d_isquicksave = value; }
}
public bool IsAutoSave
{
get { return d_isautosave; }
set { d_isautosave = value; }
}
public string Directory
{
get { return d_directory; }
set { d_directory = value; }
}
public string FullName
{
get { return d_fullname; }
set
{
d_fullname = value;
string[] split = value.Split(new char[]{'-'});
foreach (string str in split)
{
if (System.Text.RegularExpressions.Regex.IsMatch(str, "^\\d\\d:\\d\\d:\\d\\d$"))
{
d_gametime = str;
}
}
}
}
public int Weirdnumber
{
get { return d_weirdnumber; }
set { d_weirdnumber = value; }
}
public string Owner
{
get { return d_owner; }
set { d_owner = value; }
}
}
Gametime is that special property I mentioned earlier. It doesn't have a set function, but according to this, I should be in the clear, right?
Can anyone then tell me why I may not be able to edit any of the DGV cells?
EDIT: I just found out that not setting AutoGenerateColumns to false allows me to edit again, but I still don't know why.
After several hours, a friend finally took a look at it over Remote Desktop. He wrote a function to force all columns to have a non read-only status, and go figure, it worked. So we looked at the column properties in the editor, and somehow... I don't know why... they were all set to Read only. I swear I checked them 4 times before.
The lesson of this story (I guess): When in doubt, check your settings. When not in doubt, become doubtful. Otherwise, file a bug report to Microsoft :\

Can't alter DisplayMember in WinForms ComboBox

I'm trying to alter how a combobox is displayed using the following code:
private void UpdateMapRoadPointList(List<GeographicAddress> plstMapRoadPointList)
{
cboFind.DataSource = plstMapRoadPointList;
cboFind.DisplayMember = "ShortCode";
cboFind.ValueMember = "";
}
GeographicAddress is a class which has a ShortCode property which returns a string:
internal string ShortCode
{
get { return Distance + Carriageway; }
}
However, when using the application, the disaplyed value is still coming from GeographicAddress.ToString(). On debugging, it seems that cboFind.DisplayMember = "ShortCode" is having no effect! DisplayMember is "" before and after executing that line!
What am I missing?
public string ShortCode
{
get { return Distance + Carriageway; }
}
private void UpdateMapRoadPointList(List<GeographicAddress> plstMapRoadPointList)
{
cboFind.DataSource = plstMapRoadPointList;
cboFind.DisplayMember = "ShortCode";
}
this should work
Set ShortCode property to Public or it will fail and use GeographicAddress.ToString()

Categories