Pregunta

On a C# Windows form button click, I have a SQL Server stored procedure that I use to return a Customer ID based on a Customers First Name and Last Name parameters. If the customer doesn't exist I am receiving this error

Object cannot be cast from DBNull to other types.

How do I show a message that shows Customer Not Found instead of this receiving this error.

Code to call stored procedure and store return value as memberID:

SqlCommand IDFromName = new SqlCommand("MemberIDfromName", sc);
IDFromName.Parameters.Add("@memberID", SqlDbType.Int).Direction = ParameterDirection.Output;
IDFromName.Parameters.Add("@firstName", SqlDbType.NVarChar).Value = txtFirst.Text;
IDFromName.Parameters.Add("@secondName", SqlDbType.NVarChar).Value = txtLast.Text;
IDFromName.CommandType = CommandType.StoredProcedure;

sc.Open();
IDFromName.ExecuteNonQuery();
sc.Close();

memberID = Convert.ToInt32(IDFromName.Parameters["@memberID"].Value);  
¿Fue útil?

Solución

Try This:

if (!DBNull.Value.Equals(IDFromName.Parameters["@memberID"].Value) 
{
//success Customer Found Do something
 -------------------------------------
}
else
{
MessageBox.Show("Customer Not Found!");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top