I need to find a way to set the default value of ischecked to true, I am passing it as a parameter and I don't always set it.
ischecked is defined in my config files, I have multiple configs and in some it is defined and some it isn't. I won't get into why I use different configs. When it isn't define it is defaulted to false but I need it to be true.
function showSaveCardControl(ischecked) {
$(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
if it hasn't been defined I need the checkbox to be checked basically but since the default is false it is unchecked.
Update:
I am passing an xml element to a c# property. The xml would be where I set the value of ischecked but since I haven't set it somewhere either in the xml or once it has been turned into a c# property it is set to false. I am guessing it is set as the property tries to call that xml value.
I have tried setting the default using an attribute.
[XmlElement("EasyPaySaveCardControlChecked")]
[DefaultValue(true)]
public bool ischecked { get; set; }
I have tried setting it using a constructor.
public className()
{
ischecked = true;
}
I have also tried making all the bools nullable and the value is still being set to false
none of these solutions work and I have no idea why. no matter what I do the property is set to false, if it was set to undefined it would be fine but bools have to defaulted to false
Try something like this:
function showSaveCardControl(ischecked) {
if ('undefined' === typeof ischecked) ischecked = true;
$(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
this should do the trick :
function showSaveCardControl(ischecked) {
if(typeof ischecked == 'undefined')
ischecked = true;
$(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
Assuming the property is part of a class then just set it's default value to true in the class constructor and it will be overwritten down the line if you have logic to set the value from the config.
public class LukesClass
{
public String whatever {get;set;}
public bool isChecked {get;set;}
public LukesClass()
{
isChecked = true;
}
}
Try using auto property initializers (C# 6.0 and higher):
public bool isRequired { get; set; } = true;
I had a single case where I needed an unspecified xml bool to import as true instead of false. The above code will result in isRequired being true when either the tags specify true, or when they do not exist. It will only be false when tags define it as false.
Related
Researched this error and some have said it's a bug but when I used some of their suggestions it didn't fix the problem. What should I do?
**Code
/// Indicates if the profiles has been added.
public Boolean _isNew
{
get { return _isNew; }
set { _isNew = value; }
}
/// Indicates if any of the fields in the class have been modified
public Boolean _isDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
//Gets and Sets delimiterChar
public Char _delimiterChar
{
get { return _delimiterChar; }
set { _delimiterChar = value;}
}
Error**
Ambiguity between 'ConsoleApplication3.ProfileClass.isNew'and 'ConsoleApplication3.ProfileClass.isNew
Ambiguity between 'ConsoleApplication3.ProfileClass.isDirty'and 'ConsoleApplication3.ProfileClass.isDirty
Ambiguity between 'ConsoleApplication3.ProfileClass._delimiterChar'and 'ConsoleApplication3.ProfileClass._delimiterChar
The code you have posted will cause recursion and eventual stackoverflow. You're trying to set property inside the property setter. You either need a backing field or automatic properties to achieve what you're doing. Something like:
private bool _isNew;
public Boolean IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
or
public Boolean IsNew {get; set;}
In C#, if you specify what you are getting and setting, you cannot use the same name as the property (self-reference issue). As of now, you are attempting to get and set a property to itself, which is not valid. Also a heads up about naming conventions, your public properties should not begin with an underscore, but should follow capital camel casing.
There are two answers to this, both equally valid depending on what you need to do.
METHOD 1: If you take out what it is getting and setting, C# can figure out that there is an implied field that is referenced by the IsNew property. This is essentially shorthand for METHOD 2.
public bool IsNew { get; set; } // shorthand way of creating a property
METHOD 2: Specify a field to get and set.
private bool _isNew; // the field
public bool IsNew { get => _isNew; set => _isNew = value; } // this is the property controlling access to _isNew
Read more information here: Shorthand Accessors and Mutators
Essentially, Use METHOD 1 by default if you don't need to perform any additional operations. However, if you need to provide additional functionality when getting or setting, then use METHOD 2 (I.E. look up the MVVM Pattern for an example https://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/)
I create a custom User Control which inherits from DataGridViewColumn.
Moreover, I added some properties in the control, but I can't modify them in design-time.
Even I set the default value as true, it's still false.
code:
public class ParaGridViewColumn : DataGridViewColumn
{
private bool _Necessary;
private bool _ReadOnlyEmpty;
[Description("Default cell status."), Category("Behavior"), DefaultValue(false)]
public bool Necessary { get { return _Necessary; } set { _Necessary = value;} }
[Description("When ReadOnly is true, clear value on the cell or not."), Category("Behavior"), DefaultValue(true)]
public bool ReadOnlyEmpty { get { return _ReadOnlyEmpty; } set { _ReadOnlyEmpty = value; }}
public ParaGridViewColumn()
{
this.CellTemplate = new ParaGridViewCell();
}
}
The new properties can shown on the window, but their default value are false.
I change them to true, entering and opening this window again, it's still false.
However, I can modify other properties regularly. It means I didn't lock this control.
Why is that?
Did I make something wrong?
Thanks a lot.
The first problem is with [DefaultValue(true)] for ReadOnlyEmpty while not setting the true value for it.
You have not set the default value for property to true.
In fact [DefaultValue(true)] help to CodeDomeSerizalizer to serialize value for this property if the property value is not equals to this default value.
You should set ReadOnlyEmpty= true in constructor or _ReadOnlyEmpty instead.
private bool _ReadOnlyEmpty=true;
The problem here is when you set property to true in property grid, when closing the form, serializer will not serialize true value, because you said it is default but you have not set it to true, so it will remain false.
The second problem is that if you want values persist, you should override Clone of base class and provide a clone copy that contains your custom properties.
public override object Clone()
{
ParaGridViewColumn column = (ParaGridViewColumn)base.Clone();
//Uncomment if you have ParaGridViewCell
//column.CellTemplate = (ParaGridViewCell)CellTemplate.Clone();
column.Necessary = this.Necessary;
column.ReadOnlyEmpty = this.ReadOnlyEmpty;
return column;
}
Well, I found the solution, losing an override clone function.
public override object Clone()
{
ParaGridViewColumn c = (ParaGridViewColumn)base.Clone();
c._Necessary = this._Necessary;
c._ReadOnlyEmpty = this._ReadOnlyEmpty;
return c;
}
I'm writing an application, where I have quite a lot Properties of Type Boolean defined:
private bool kajmak = true;
public bool Kajmak
{
get { return kajmak ; }
set { kajmak = value; FirePropertyChanged(() => Kajmak); }
}
As you see, I set kajmak to true at the beginning..-the reason is nonrelevant-. (You might know that the default value of a bool variable is false).
Now, is there a way, to change the default value of a bool to true? So I would write:
private bool kajmak; //kajmak = true
instead of
private bool kajmak = true;
What could I do to achieve this?
C Sharp 6.0 has introduced a nice new way to do this:
public bool YourBool { get; set; } = true;
This is equivalent to the old way of:
private bool _yourBool = true;
public bool YourBool
{
get { return _yourBool; }
set { _yourBool = value; }
}
see this article http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx
Because booleans are false by default, I use positive forms in my names, like IsInitialized, HasSomething etc. which I want to be false by default until I explicitly set them.
If you find you need something to be true by default, maybe you need to rename your variable so it makes more sense when the default is false.
In service:
public bool Kajmak { get; set; } = true;
No. There's no way to change the default value assigned by .NET. Your best bet is to either assign the appropriate default in the private member:
private book kajmak = false;
Or use the Constructor like you're supposed to and assign the class defaults there:
public class SomeClass
{
public SomeClass()
{
Kajmak = false;
}
public book Kajmak { get; set; }
}
No, there's no possibility to change the default value. If you could change the default-value, it wouldn't be the default anymore ;).
But to set the default-value to null, you could use this:
bool? kajmak;
But that's not what you want...
In the process of trying to do something similar, a colleague enlightened me to the bool? type. It can be true, false, or null, and does not object to being on the left side of such a comparator. This does not answer your question of how to default bool to true, but does solve your conceptual problem of wanting your variables to be definable as true by default.
I only post because this was the top result when I searched, and this information was helpful to me. Hopefully it will be to others who find this page.
You may create a class myBool that defaults to false and an implicit conversion from bool to your class.
As the topic suggests I have some problems with PropertyInfo.SetValue. To get to the point, here is my example - I have created my own class and the main thing about it is the presentation object:
using System;
using System.Reflection;
namespace TestingSetValue
{
public class Link
{
private object presentationObject = null;
private string captionInternal = string.Empty;
public Link (string caption)
{
captionInternal = caption;
}
public string CaptionInternal
{
get { return captionInternal; }
set { captionInternal = value; }
}
public bool Visible
{
get
{
if (PresentationObject != null)
{
PropertyInfo pi = PresentationObject.GetType().GetProperty("Visible");
if (pi != null)
{
return Convert.ToBoolean(pi.GetValue(PresentationObject, null));
}
}
return true;
}
set
{
if (PresentationObject != null)
{
PropertyInfo pi = PresentationObject.GetType().GetProperty("Visible");
if (pi != null)
{
pi.SetValue(PresentationObject, (bool)value, null);
}
}
}
}
public object PresentationObject
{
get { return presentationObject; }
set { presentationObject = value; }
}
}
}
Then, I do this:
private void btnShowLink_Click(object sender, EventArgs e)
{
Link link = new Link("Here I am!");
this.contextMenu.Items.Clear();
this.contextMenu.Items.Add(link.CaptionInternal);
link.PresentationObject = this.contextMenu.Items[0];
link.Visible = true;
lblCurrentVisibility.Text = link.Visible.ToString();
}
Now, I can imagine this doesn't look too logical/ economical, but it shows the essence of my real problem. Namely, why doesn't the visibility of presentation object (and the value of link.Visible) change, after I call:
link.Visible = true;
I simply do not know what else to do to make this work... Any help is deeply appreciated.
To make things even more interesting, the property Enabled behaves as expected of it...
PropertyInfo pi = PresentationObject.GetType().GetProperty("Enabled");
Could it be related to the fact that Visible is actually a property of ToolStripDropDownItem base base object, whereas Enabled is 'direct' property of ToolStripDropDownItem ?
It would have been easier to figure this out if you said upfront what class this is but now we know it is ToolStripDropDownItem which we can infer means WinForms.
What you are seeing is an oddity with the ToolStripItem's Visible property. It's setter & getter are not tied directly together. MSDN says
"The Available property is different from the Visible property in that
Available indicates whether the ToolStripItem is shown, while Visible
indicates whether the ToolStripItem and its parent are shown. Setting
either Available or Visible to true or false sets the other property
to true or false."
In other words, you want to use the Available property instead of the Visible property
Check http://msdn.microsoft.com/en-us/library/system.web.ui.control.visible.aspx. Maybe this is causing your problem.
There is very important piece of info:
If this property is false, the server control is not rendered. You should take this into account when organizing the layout of your page. If a container control is not rendered, any controls that it contains will not be rendered even if you set the Visible property of an individual control to true. In that case, the individual control returns false for the Visible property even if you have explicitly set it to true. (That is, if the Visible property of the parent control is set to false, the child control inherits that setting and the setting takes precedence over any local setting.)
I'm having this wierd problem... in my code whether I set the value of IsRequired to false or true then it stays false.. However if I put in a DefaultValue it works?
The non-working code is:
public class FtpSettingsSection : ConfigurationSection
{
[ConfigurationProperty("host", IsRequired = true)]
public HostElement Host
{
get { return (HostElement)this["host"]; }
set { this["host"] = value; }
}
}
public class HostElement : ConfigurationElement
{
[ConfigurationProperty("URL", IsRequired = true)]
public string URL
{
get { return (string)this["URL"]; }
set { this["URL"] = value; }
}
}
and the working code is:
public class FtpSettingsSection : ConfigurationSection
{
[ConfigurationProperty("host", DefaultValue = "", IsRequired = true)]
public HostElement Host
{
get { return (HostElement)this["host"]; }
set { this["host"] = value; }
}
}
public class HostElement : ConfigurationElement
{
[ConfigurationProperty("URL", DefaultValue = "", IsRequired = true)]
public string URL
{
get { return (string)this["URL"]; }
set { this["URL"] = value; }
}
}
How come that I need to set DefaultValue to ""?
I have encountered the same problem and found the solution here http://msdn.microsoft.com/en-us/library/system.configuration.configurationpropertyattribute%28v=vs.90%29.aspx#1. The comment on ConfigurationPropertyAttribute isn't completely correct, but it explains the basics of the problem:
The IsRequired member of ConfigurationPropertyAttribute does not work when applied to a child object (deriving from ConfigurationElement). When the subsystem reflects over the attributes of the parent section/element to determine which configuration properties are defined it will create a new instance (of the appropriate type) for each child element and store it in the parent's value list. Later, when it validates whether all required properties have been specified or not, it cannot differentiate between a default initialized child element and one that was explicitly contained in the configuration file.
The most ideal workaround would be to programmatically declare the required elements through the ConfigurationProperty class. This requires substantial more work than the declarative approach. An alternative...
As far as I can tell the alternative is incorrect.
An example of the programmatic model can be found on the ConfigurationProperty page. I have managed to fix the problem for myself by declaring the properties I need required in the constructor of my custom element and leaving everything else the same.
I suspect for you it is not actually working when you add DefaultValue, but rather throwing an exception for a different reason. You will have to drill down to the end of the InnerException chain to find the ConfigurationErrorsException. The correct message when a required property is missing is "Required attribute 'host' not found. (C:\path\to\yourproject\bin\Debug\yourproject.vshost.exe.Config line ##)"
When you provide an empty string default value the configuration subsystem will try to parse that string into a HostElement and fail. The resulting ConfigurationErrorsException has the message "The default value of the property 'host' cannot be parsed. The error is: Object reference not set to an instance of an object. (C:\path\to\yourproject\bin\Debug\yourproject.vshost.exe.Config line ##)"
Digging up a dead thread.
But I accidentally found a work around for this.
In your custom section constructor, make a reference to a custom element's ElementInformation. By doing that, another instance of your custom section will created in the element's context. And for some reason that I don't understand fully, the IsRequired property is honored.
public class FtpSettingsSection : ConfigurationSection
{
public FtpSettingsSection()
{
// force it to double load.
if (this.Host.ElementInformation.IsPresent) ;
}
[ConfigurationProperty("host", IsRequired = true)]
public HostElement Host
{
get { return (HostElement)this["host"]; }
set { this["host"] = value; }
}
}
Sorry for necroposting, but this problem hit me too but in a more peculiar way and my solution also applies to the question asked.
I implemented reloading a config without restarting a process.
When the process starts, the IsRequired attribute is "ignored" and the ConfigurationElement is silently initialized with default values. But when the config is reloaded, the IsRequired attributed is respected! So I hardcoded reloading configuration on process start and it solved the problem of missing exception!
Pseudocode:
config = (SampleConfiguration)ConfigurationManager.GetSection(ConfigSectionName);
// <-- no exception thrown for missing required properties
ConfigurationManager.RefreshSection(ConfigSectionName);
config = (SampleConfiguration)ConfigurationManager.GetSection(ConfigSectionName);
// <-- exception thrown!
I am assuming you dont have the URL propertie's value serialized in your configuration. So when the configuration is being loaded the ConfigurationManager checks the attributes to see if the property value required and then throws exception if finds no value. If default value is set, then that value is used if none found in the config.