Reputation: 495
Say I have a list made up of a listitem which contains three strings. I add a new listitem, and try to assign the values of said strings from an outside source.
If one of those items is unassigned, the value in the listitem remains as null (unassigned). As a result I get an error if I try to assign that value to a field on my page.
I can do a check on isNullOrEmpty for each field on the page, but that seems inefficient. I'd rather initialize the values to "" (Empty string) in the codebehind and send valid data.
I can do it manually:
ClaimPwk emptyNode = new ClaimPwk();
emptyNode.cdeAttachmentControl = "";
emptyNode.cdeRptTransmission = "";
emptyNode.cdeRptType = "";
headerKeys.Add(emptyNode);
But I have some BIG list items, and writing that for those will get tedious.
So is there a command, or just plain an easier way to initialize a listitem to empty string as opposed to null?
Or has anyone got a better idea?
Upvotes: 0
Views: 238
Reputation: 12904
Return an initialised (with proper values, string.Empty if required) instance of the class from the outside source and add it directly to the collection.
classCollection.Add(GetClassInstanceFromOutsideSource());
If you are unable to return an instance from this outside source, write a wrapper method to call it, return instance and add this directly to the collection.
I am unable to think of any reason why you would want to add, what is in essence an 'empty' instance of your class into a collection then update it afterwards. Inefficient and illogical.
Upvotes: 2
Reputation: 108957
Could be a bit of a stretch but you can use reflection to set all public writeable string properties to string.Empty
like this
emptyNode.GetType()
.GetProperties()
.Where(p => p.CanWrite && p.PropertyType == typeof(string)).ToList()
.ForEach(p => p.SetValue(emptyNode, string.Empty, null));
But the most efficient option would be to initialize the properties to string.Empty in the class definition.
Upvotes: 1
Reputation: 8786
you could set your properties with default value (""
in your case) when you defined them in your ClaimPwk
Class
e.g.
Public Class ClaimPwk{
public string cdeAttachmentControl = "";
public string cdeRptTransmission = "";
public string cdeRptType = "";
}
then when you create an instance of ClaimPwk
you will have those properties with default value ""
Upvotes: 1