2012-04-02 3 views
0

내 애플리케이션은 이미지 데이터를 데이터베이스에 저장하고 정보를 폼에로드 할 때 패널에 이미지를로드합니다. 이것은 잘 작동합니다. 하지만 사용자가 이미지를 저장하고 싶지 않은 경우 데이터베이스의 이미지 필드 (varbinary)에 '0'을 삽입했습니다. 이 정보 (0x00000000)를 데이터베이스에서로드하는 동안 다음 예외가 throw됩니다.데이터베이스에서 패널로 이미지로드

"매개 변수가 유효하지 않습니다." 데이터베이스에

저장 이미지 : 여기

나는 코드의 일부 조각을주고있다

if(user has selected an image) 
{ 
    Byte[] imageBytes = File.ReadAllBytes(imagePatient); 
    sqlCommand.Parameters.AddWithValue("Img", imageBytes); //Img is database column for images 
} 
else 
{ 
    sqlCommand.Parameters.AddWithValue("Img", 0); 
} 

로드 이미지를 데이터베이스에서 : 나는 몇 가지 체크를 넣어 시도했습니다

Byte[] imageData = new Byte[0]; 
imageData = (Byte[])(dataSet.Tables["Patients"].Rows[0]["Img"]); 
MemoryStream stream = new MemoryStream(imageData); 
panelImage.BackgroundImage = Image.FromStream(stream); 

데이터가 제로 형식이 아닌 경우에만 BackgroundImage를로드 할 수 있습니다.

이 문제를 어떻게 해결할 수 있습니까?

답변

1

0 대신 NULL을 저장합니다.

if(user has selected an image) 
{ 
    Byte[] imageBytes = File.ReadAllBytes(imagePatient); 
    sqlCommand.Parameters.AddWithValue("Img", imageBytes); //Img is database column for images 
} 
else 
{ 
    sqlCommand.Parameters.Add("Img", SqlDbType.VarBinary, -1); 
    sqlCommand.Parameters["Img"].Value = DbNull.Value; 
} 

그리고 null 이외의 여부를 확인하기 위해 if 문을 사용

Byte[] imageData = new Byte[0]; 
imageData = (Byte[])(dataSet.Tables["Patients"].Rows[0]["Img"]); 
if(imageData != null) 
{ 
    MemoryStream stream = new MemoryStream(imageData); 
    panelImage.BackgroundImage = Image.FromStream(stream); 
} 

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx

+0

당신은 NULL을 저장 생각하지 것은 적절한 옵션입니다합니까? –

+0

"여기에 데이터가 없습니다."라고 말하기 때문에이 경우 적합합니다. – msigman

+0

이 데이터베이스 테이블에 열이 10 개 있습니다. –