KAKA
KAKA

Reputation: 131

How can i fix Unable to cast object of type 'System.DBNull' to type 'System.String`

I get trying to get data using the following code

Unable to cast object of type 'System.DBNull' to type 'System.String`

private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {

            if (e.IsGetData)
            {
                DataRow row = ((DataRowView)e.Row).Row as DataRow;

                string value = (string)row["BOM - RIM PN"]; 
                var results = from myRow in this.wHLMASTERDETAIL.RIMS.AsEnumerable()
                              where myRow.Field<string>("STOCK NO") == value
                              select myRow;
                e.Value = results.ToList().Count;
            }

Upvotes: 1

Views: 15385

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 27009

Check if it's DBNull firstly and return an empty string or whatever is appropriate in your case. Otherwise call ToString() on it.

var boxRim = row["BOM - RIM PN"];
string value  = (bomRim == DBNull.Value) ? string.Empty : bomRim.ToString();

Upvotes: 1

vadim
vadim

Reputation: 176

try

string value = row["BOM - RIM PN"].ToString();

In case you need some extra work for null values(maybe skip them) you need additional type check.

Upvotes: 3

Related Questions