10

データベースからに画像をロードしようとしていますPictureBox。これらの次のコードを使用して、写真にロードします。いくつかのコードを書きましたが、続行するために何をすべきかわかりません。

どんな助けでも大歓迎です。

private void button1_Click(object sender, EventArgs e)
    {
        sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
        cmd = new SqlCommand();
        cmd.Connection = sql;
        cmd.CommandText = ("select Image from Entry where EntryID =@EntryID");
        cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text));
    }
4

3 に答える 3

16

button1_Clickで次のようなものを続行します。

// Your code first, here.

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"];
    var stream = new MemoryStream(data);
    pictureBox1.Image = Image.FromStream(stream);
} 
于 2012-05-04T19:12:51.280 に答える
4

という名前のテーブルを持つ単純なデータベースがあると仮定しますBLOBTest

CREATE TABLE BLOBTest
(
BLOBID INT IDENTITY NOT NULL,
BLOBData IMAGE NOT NULL
)

次の方法で、画像をコードに取得できます。

try
{
    SqlConnection cn = new SqlConnection(strCn);
    cn.Open();

    //Retrieve BLOB from database into DataSet.
    SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);   
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds, "BLOBTest");
    int c = ds.Tables["BLOBTest"].Rows.Count;

    if(c>0)
    {   //BLOB is read into Byte array, then used to construct MemoryStream,
        //then passed to PictureBox.
        Byte[] byteBLOBData =  new Byte[0];
        byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
        MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
        pictureBox1.Image= Image.FromStream(stmBLOBData);
    } 
    cn.Close();
}
catch(Exception ex)
{MessageBox.Show(ex.Message);}

BLOBTestこのコードは、データベースのテーブルから に行を取得し、DataSet最後に追加された画像をByte配列にコピーしてからオブジェクトにコピーし、次に をコントロールのプロパティにMemoryStreamロードします。MemoryStreamImagePictureBox

完全なリファレンス ガイド:

http://support.microsoft.com/kb/317701

于 2012-05-04T19:02:41.507 に答える