I want to insert null value in varbinary(max) but it is returning an error.
I am trying the code below to save the photo, when I attach photo it saves without any issue. When there is no photo it throws an error.
Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
protected void Button3_Click(object sender, EventArgs e)
{
newphoto pat = new newphoto();
pat.id = id.Text;
byte[] photo = null;
if (Attch.HasFile)
{
Stream fs2 = Attch.PostedFile.InputStream;
BinaryReader br2 = new BinaryReader(fs2);
pat.photo = br2.ReadBytes((Int32)fs2.Length);
}
else
{
pat.photo = null;
}
pat.Addfile()
}
public bool Addfile()
{
Parameters.Clear();
Parameters.AddWithValue("@pat_id", id);
if (photo == null)
{
Parameters.Add("@photo", SqlDbType.VarBinary, -1);
Parameters["@photo"].Value = DBNull.Value;
}
else
{
Parameters.AddWithValue("@photo", photo);
}
return FetchNonQuery(@"insert into mr_Info (@pat_id ,@photo)" +
" Values (@pat_id ,@photo)");
}
protected bool FetchNonQuery(string CmdQuery)
{
bool result = false;
using (SqlConnection myConnection = DBConnection)
{
SqlCommand myCommand = new SqlCommand(CmdQuery, myConnection);
myCommand.CommandType = CommandType.Text;
//Set Parameters
foreach (SqlParameter Parameter in _parameters)
{
myCommand.Parameters.AddWithValue(Parameter.ParameterName, Parameter.Value);
}
//Execute the command
myConnection.Open();
if (myCommand.ExecuteNonQuery() > 0)
{
result = true;
}
myConnection.Close();
}
return result;
}