Home > Software design >  DBNull exception when passing null value in DB
DBNull exception when passing null value in DB

Time:02-07

I have this piece of code and I am getting exception for featureValue.IsVisible. I know that I need to verify to not be DbNull.Value or assing a Value if they are. But I don't know how to do this verifications in my context where I have code in Linq

ComboBoxEdit comboBox = new ComboBoxEdit();


var featureValues = 
        from featureValue in this.productsDataSet.FeatureValues
        where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible == true) 
        select featureValue.Value;

comboBox.Properties.Items.AddRange(featureValues.ToArray());
comboBox.Properties.AutoComplete = true;
comboBox.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;

return comboBox;

I tried :

 !IsDbNull(featureValue.IsVisible)
 !IsNull(featureValue.IsVisbile)

The name 'IsNull' does not exist in the current context

 featureValue.isVisbile == DBNull.Value

Operator '==' cannot be applied to operands of type 'bool' and 'DBNull'

!featureValue.IsNull(featureValue.IsVisible)

Cannot convert from 'int' to 'bool' I am getting errors for all

CodePudding user response:

You could try the following

var featureValues = 
    from featureValue in this.productsDataSet.FeatureValues
    where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible.HasValue && featureValue.IsVisible == true) 
    select featureValue.Value;

CodePudding user response:

Since featureValue.IsVisible have possible DbNull.Value then you have to check for DbNull before moving on using System.Convert class

If your exception is at featureValue.IsVisible then this section of code snippet:

var featureValues = 
        from featureValue in this.productsDataSet.FeatureValues
        where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible == true) 
        select featureValue.Value;

would be:

var featureValues = 
        from featureValue in this.productsDataSet.FeatureValues
        where (featureValue.FeatureId == feature.FeatureId && !Convert.IsDBNull(featureValue.IsVisible) && featureValue.IsVisible == true) 
        select featureValue.Value;

Which basically means before evaluate the featureValue.IsVisible == true, it will check if is NOT DbNull. When if it is DBNull, then && operator will cutshort and will not evaluate featureValue.IsVisible == true

  •  Tags:  
  • Related