2013-03-17 69 views
1

我在SQL Server中存儲了一個映像。首先,我已經將圖像轉換爲字節,並將其保存在SQL Server中,並且在保存時完成了很多工作.....當我嘗試從SQL Server中調用各自圖像的字節值時,在C#中,我由用戶代碼越來越像從數據庫調用字節時發生錯誤

的NullReferenceException一個錯誤是未處理的未設置爲一個對象

下面的實例

對象引用是我的代碼:

protected void GetImageButton_OnClick(object sender, EventArgs e) 
{ 
    SqlConnection connection = new SqlConnection(); 
    connection.ConnectionString = @""; 
    connection.Open(); 
    SqlCommand command = new SqlCommand(); 
    command.Connection = connection; 
    command.CommandType = CommandType.StoredProcedure; 
    command.CommandText = "uspgetimage"; 
    command.Parameters.AddWithValue("@imageID", getimagebutton.Text); 
    DataSet dataset = new DataSet(); 
    SqlDataAdapter adapter = new SqlDataAdapter(); 
    adapter.SelectCommand = command; 
    adapter.Fill(dataset); 
    Byte[] bytes = command.ExecuteScalar() as byte[]; 
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length); 
    Image.ImageUrl = "data:image/jpeg;base64," + base64String; 
} 

請看看它,並幫助我擺脫這個朋友。

+2

這個問題的任何值,由Soner格尼爾編輯似乎很很熟悉。我現在有10個Deja-Vus。告訴我你以前是否問過這個問題? – 2013-03-17 09:14:12

+0

閱讀這個問題http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net調試你的代碼,並找到哪一行拋出_exception_並修復它。可能你的一個變量是'null',並且在初始化之前嘗試使用它。 – 2013-03-17 09:18:02

+0

你可以發佈stacktrace嗎?或更好地發佈您的存儲過程..可能是這部分返回null:'Byte [] bytes = command.ExecuteScalar()as byte [];' – 2013-03-17 09:21:44

回答

0

之前NullReferanceException,我不相信這行拋出任何異常..

SqlConnection connection = new SqlConnection(); 
connection.ConnectionString = @""; 
connection.Open(); 

初始化SqlConnection.ConnectionString屬性之前無法打開連接。在你的情況下,你的連接字符串是空字符串。你如何期待這個連接連接到你的SQL服務器?

我的建議是,讀一本關於C#和使用數據庫使用它像Begining C# 5.0 Databases

對於NullReferanceException,我已經提到我comment你應該做的。

+0

Imho,我認爲OP要隱藏他的連接字符串... :) – 2013-03-17 09:29:55

+0

恕我直言,我認爲OP不知道他想要什麼.. – 2013-03-17 09:31:11

+0

我只是隱藏了我的連接... btw,它現在工作正常..問題是隻用程序...非常感謝您的幫助朋友:) – 2013-03-18 05:45:54

0

您可能會收到ExecuteScalar的電話NullReferenceException。從the documentation

返回值

第一行的結果集,或空引用第一列...如果結果集爲空

強調我的。

而對於它的價值,SqlConnectionSqlCommandDataSetSqlDataAdapter都是IDisposable。你應該打電話給Dispose,雖然the value of disposing DataSet is arguable

+0

問題是隻與程序...我清除它,現在的錯誤已經完成.....非常感謝您的幫助朋友: ) – 2013-03-18 06:23:43

0

嘗試運行在SQL Server存儲過程,看它是否返回使用

EXEC uspgetimage 'COmma seperated Parameter List'