1

I keep getting this error because the VendorID is null for that record. I've seen that this question has been asked a couple times and it seems like I should just do a check to see if null before it converts it and enters it in the dbtable, but I'm not sure how to do that.

public static PartOrder findPartOrder(string orderNo)
    {
        PartOrder aPartOrder = new PartOrder();
        OleDbDataAdapter myAdapter = new OleDbDataAdapter();
        if (aConnection.State == ConnectionState.Closed)
            aConnection.Open();
        OleDbCommand cmd = aConnection.CreateCommand();
        OleDbDataReader dbReader = null;
        cmd.CommandText = "SELECT * FROM PartOrder WHERE OrderNo = '" + orderNo + "'";
        dbReader = cmd.ExecuteReader();

        while (dbReader.Read())
        {
            aPartOrder.OrderNo = (string)dbReader.GetValue(0);
            aPartOrder.Length = (string)dbReader.GetValue(1);
            aPartOrder.Finish = (string)dbReader.GetValue(2);
            aPartOrder.Cost = (string)dbReader.GetValue(3);
            aPartOrder.PartDrawingNo = (string)dbReader.GetValue(4);
            aPartOrder.VendorId = (string)dbReader.GetValue(5);
            aPartOrder.ShopId = (string)dbReader.GetValue(6);
            aPartOrder.Completed = (string)dbReader.GetValue(7);
        }

        dbReader.Close();
        return aPartOrder;
    }

Again, the line "aPartOrder.VendorId = (string)dbReader.GetValue(5);" gets the error because VendorId is null.

0

4 Answers 4

3

for this particular line try this:

aPartOrder.VendorId = dbReader.GetValue(5)==DBNull?"":dbReader.GetValue(5).value;

better would be to write a helper function:

private static string MyToString(object o)
{
    if(o == DBNull.Value || o == null) 
       return "";

    return o.ToString();
}

and use it:

aPartOrder.VendorId = MyToString(dbReader.GetValue(5));
Sign up to request clarification or add additional context in comments.

Comments

1

One Line Answer

aPartOrder.VendorId = dbReader.IsDBNull(5) ? "" :(string)dbReader.GetValue(5);

Comments

0

dbReader.GetValue(5).HasValue ? dbReader.GetValue(5).ToString() : String.Empty

Comments

0

Use the OleDbDataReader.IsDBNull(ordinal) to verify the field value.

if(!dbReader.IsDBNull(5))
  aPartOrder.VendorId = dbReader.GetString(5);

Suggestion: Always use parameters/precompiled sql statement to prevent SQL-Injection attack.

cmd.CommandText = "SELECT * FROM PartOrder WHERE OrderNo = @OrderNo";
cmd.Parameters.Add("@OrderNo",System.Data.OleDb.OleDbType.VarChar,20).Value=orderNo;
dbReader = cmd.ExecuteReader();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.