Get cell value from Dataset - c#

I have Table in Data Set and when i try get cell value if value is null i get exception. Strong Typing Exception
"The value for column Surname in table AI_PARTNERS is Db Null."
Ever time when i try turn
partnersDataSet.AI_PARTNERS[0].SURNAME
if is null i get exception and can't do compare with null.
_partnerInfo.Surname = partnersDataSet.AI_PARTNERS[0].SURNAME
how get the value or empty string if value null?

You can always use one of the DataRow.IsNull method overloads. Also, since you are using typed data set, there must be a generated method called IsSURNAMENull().
But you can get that automatically. Open the typed dataset xsd file in the designer, select the SURNAME property, go to Properties window and change the NullValue property from (Throw exception) (the default) to either (Null) or (Empty).
Reference: Annotating Typed DataSets

try like this
Check your properties with DBNull.Value value
if(partnersDataSet.Tables[0].Rows.Count>0)
{
if(!string.IsNullOrEmpty(partnersDataSet.AI_PARTNERS[0].SURNAME))
{
if (partnersDataSet.AI_PARTNERS[0].SURNAME != System.DBNull.Value))
{
_partnerInfo.Surname =partnersDataSet.AI_PARTNERS[0].SURNAME;
}
}
}

Related

Get property value of a complex type with reflection in c#

I have an object like this
oldEntity
Active: true
ActiveDirectoryName: ""
ArchiveConceptValueList: null
AsgScndCnpRangeDictionary: Count = 0
AssignedRuleList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedRule>}
AssignedScndCnpRangeList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedScndCnpRange>}
AssignedScndCnpRangePeresentList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedScndCnpRange>}
AssignedWGDShiftList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedWGDShift>}
AssignedWorkGroupList: {GTS.Clock.Model.PersonWorkGroup, GTS.Clock.Model.PersonWorkGroup}
Assistant: null
BarCode: "0451343786"
BasicTrafficController: {GTS.Clock.Model.Concepts.BasicTrafficController}
BasicTrafficList: {}
BudgetList: null
CFPNeedUpdate: false
CalcDateZone: null
CardNum: "2465"
CartOrgan: {GTS.Clock.Model.Charts.Department}
CheckEnterAndExitInRequest: false
CostCenter: {GTS.Clock.Model.BaseInformation.CostCenter}
CurrentActiveContract: null
CurrentActiveDateRangeGroup: null
CurrentActiveRuleGroup: null
CurrentActiveWorkGroup: null
CurrentRangeAssignment: null
CurrentYearBudgetList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.Concepts.CurrentYearBudget>}
DelayCartableList: {}
Department: {GTS.Clock.Model.Charts.Department}
DepartmentID: 0
...
And I want the name fiel of Department.
Besides Department in oldEntity like this:
and properies of Department field like this:
once I use below code to get name field of Department with Reflection ,I got this erro
oldEntity.GetType().GetProperty("Department").GetValue("Name", null);
Object does not match target type.
You're trying to get the value of a property as if it were a property of string - the first argument to GetValue needs to be the object you're fetching the property from (oldEntity in this case). So you can get the department like this:
object department = oldEntity.GetType().GetProperty("Department").GetValue(oldEntity, null);
To get the Name property (which I hope is a property and not a public field) you need to do the same kind of thing again:
object name = department.GetType().GetProperty("Name").GetValue(department, null);
However, you could do this all somewhat more simply using dynamic typing:
dynamic entity = oldEntity;
string name = entity.Department.Name;
Note that there's no compile-time checking for the Department or Name parts (or that the resulting type is string) but that's the same as for the reflection-based code anyway. The dynamic typing would just do the reflection for you at execution time.

Object reference not set to an instance of an object while reading file properties from SP2010

I have sharepoint document library which has custom field called "DocumentType" this is not mandatory field. When I am trying to read this property using the below code, when value is there in this field its working fine but where its value empty giving the error "Object reference not set to an instance of an object." If value is not there I need to pass empty string for further logic, how can I handle this?
SPFile spFile=Web.GetFile(Context.Request.Url.ToString());
string spDocumentType=string.Empty;
if (spFile.Properties["DocumentType"].ToString() == "INV") *In this line exception throwing where value is empty in this field in the doc library.
{
spDocumentType = spFile.Properties["DocumentType"].ToString();
}
do like this:
if(spFile.Properties["DocumentType"] !=null)
{
spDocumentType = spFile.Properties["DocumentType"].ToString() == "INV" ? spFile.Properties["DocumentType"].ToString() : "";
}
else
{
spDocumentType ="";
}
Change this piece of code:
spFile.Properties["DocumentType"].ToString()
To this:
Convert.ToString(spFile.Properties["DocumentType"])
While ToString() throws the exception you're getting when the value is null, the Convert.ToString() method tests for null and returns an empty string.

Object reference is not set into instance of an object

I am retrieving data from database table.
By giving input as 1 in
textbox1(voucherno)-->damagedetail =
web.getdamageddetail(Convert.ToInt32(voucherno.Text));
I want get branchno as output in textbox2(branchno)
branchno.Text = damagedetail.branchno.ToString();
but am getting error
Object reference is not set into instance of an object.
Check my second line.
Is second line coding correct?
damagedetail.branchno is null.
Try this:
if (damagedetail.branchno != null)
branchno.Text = damagedetail.branchno;
else
branchno.Text = "abcd";
Either your object property is not filled thus when you retrive the value "branchno" from the object the value is equal to null, or your not filling the property in your "getdamageddetail" method

not setting date property to object results in error

I have a table that has a smalldatetime NOT NULL field with a default value of getdate(). When creating a new record in the table, I don't set the smalldatetime field in code through LINQ To SQL syntax, I just let the database set the default value which is the current date. If I don't explicitly set it in code, it throws the following error:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
If I am setting a default in the database, why should I have to set it in code? I have noticed funky things with dates when it comes to LINQ To SQL.
Rather than setting the field as IsDbGenerated, you may want to consider setting its AutoSync value to OnInsert. IsDbGenerated won't let you set the field's value ever (which may be what you want for a "created date" field, but not for a "last modified" field).
However, if you're using an ORM, I would ask you to consider whether you want your application logic in both the database and the application code. Does it make more sense to implement the default value in code (via partial methods like Insert[Entity])?
You have to set the generated property so that LINQ to SQL doesn't send its default value along for creation.
The property is called "Auto Generated Value" on the entity.
To get around this, ensure that your LINQ To SQL model knows that your smalldatetime field is auto-generated by the database.
Select the table's field in your LINQ To SQL diagram, and find the Properties window. Adjust the Auto Generated Value property to True. This will ensure that the field IS NOT included in the INSERT statement generated by LINQ To SQL.
Alternately, you'd have to specify this yourself:
if (newCustomer.DateTimeCreated == null) {
newCustomer.DateTimeCreated = DateTime.Now; // or UtcNow
}
LINQ To SQL does not observe database defaults in a way that you can then subsequently update the value. In order to allow this, you need to set default values in your code.
When creating new objects that are NOT NULL with a database default, C# will use default values, such as MinValue for numbers and dates, empty GUIDs (zeros), etc. You can look for these conditions and replace with your own default value.
This is a known design issue with LINQ To SQL. For an in-depth discussion, see this link:
http://www.codeproject.com/KB/linq/SettingDefaultValues.aspx
Some example code for setting default values in your application:
private void SetDefaults(object LinqObj)
{
// get the properties of the LINQ Object
PropertyInfo[] props = LinqObj.GetType().GetProperties();
// iterate through each property of the class
foreach (PropertyInfo prop in props)
{
// attempt to discover any metadata relating to underlying data columns
try
{
// get any column attributes created by the Linq designer
object[] customAttributes = prop.GetCustomAttributes
(typeof(System.Data.Linq.Mapping.ColumnAttribute), false);
// if the property has an attribute letting us know that
// the underlying column data cannot be null
if (((System.Data.Linq.Mapping.ColumnAttribute)
(customAttributes[0])).DbType.ToLower().IndexOf("not null") != -1)
{
// if the current property is null or Linq has set a date time
// to its default '01/01/0001 00:00:00'
if (prop.GetValue(LinqObj, null) == null || prop.GetValue(LinqObj,
null).ToString() == (new DateTime(1, 1, 1, 0, 0, 0)).ToString())
{
// set the default values here : could re-query the database,
// but would be expensive so just use defaults coded here
switch (prop.PropertyType.ToString())
{
// System.String / NVarchar
case "System.String":
prop.SetValue(LinqObj, String.Empty, null);
break;
case "System.Int32":
case "System.Int64":
case "System.Int16":
prop.SetValue(LinqObj, 0, null);
break;
case "System.DateTime":
prop.SetValue(LinqObj, DateTime.Now, null);
break;
}
}
}
}
catch
{
// could do something here ...
}
}

insert null value when no selected value from ddl

I had ddl which determine gender and user can donot choose any value from ddl so i tried to check if user didnot select any value from ddl inser null value or any value in database i made that but error apear(Procedure or Function 'InsertRegisteration' expects parameter '#Gender_Id', which was not supplied).any one help me
(My Code)
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value=null;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Try this:
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value= DBNull.Value;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Added : Difference between null and System.DbNull.Value
Well, null is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.
Try this:
if (DDLGender.SelectedIndex == 0 )
{
command.Parameters.Add("#Gender_Id", DBNull.Value);
}
else
{
command.Parameters.Add("#Gender_Id", (int)DDLGender.SelectedValue);
}
You don't have to specify the data type for parameters.
Assuming you are using stored procedure for updating,
I think you can make the change in stored procedure to have default value to this INT column as NULL which will make this parameter optional. Then you can execute only the ELSE part here from code.
You can combine the above lines of code to :
cmd.Parameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, Value = DDLGender.SelectedIndex!=0 ? (int)DDLGender.SelectedValue : null });
The use of Null coalescing operator will do the null check. If the selectedItem is not null then that will be passed in as value otherwise null will be passed.

Categories