c#FromStream(stream)参数无效?

时间:2017-03-26 19:20:09

标签: c# database visual-studio

首先,方法preEntities()将新记录插入到Entities表中。插入值之一是图像。 visual studio数据库中此列的数据类型为' image'。

方法loadPanel()应该从表中的每个记录中获取图像(WHERE TYPE = OBSTACLE)并使用该图像创建一个图片框。但是,FromStream()方法中存在错误:" INVALID PARAMETER&#34 ;;我在错误出现的地方发表评论。我搜索了之前有关此错误的问题,但我找不到任何有助于我的信息:(

    private void preEntities() {
        string constring = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename="
             + "|DataDirectory|\\DonaldJump.mdf;Integrated Security=True;Connect Timeout=30";
        SqlConnection con = new SqlConnection(constring);
        con.Open();
        byte[] image = ImageToByteArray(Properties.Resources.Pipe);
        string q = "INSERT INTO dbo.Entities(Name, Type, Image, Width, Height) VALUES('Pipe','Obstacle','" + image + "','97','150')";
        SqlCommand cmd = new SqlCommand(q, con);
        cmd.ExecuteNonQuery();
    }

    private byte[] ImageToByteArray(System.Drawing.Image imageIn) {
        using (var ms = new MemoryStream()) {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
    }

     private void loadPanel() {
        string constring = "Data Source (LocalDB)\\MSSQLLocalDB;AttachDbFilename="
             + "|DataDirectory|\\DonaldJump.mdf;Integrated Security=True;Connect Timeout=30";
        SqlConnection con = new SqlConnection(constring);
        con.Open();
        string q = "SELECT * FROM dbo.Entities WHERE Type='obstacle';";

        DataTable dt = new DataTable();
        using (var command = new SqlCommand(q, con)) {
            using (SqlDataReader dr = command.ExecuteReader()) {
                dt.Load(dr);
            }
        }

        foreach (DataRow dr in dt.Rows) {
            PictureBox pb = new PictureBox();
            pb.Location = new Point(10, 10); 
            pb.Size = new Size(50, 50);
            pb.SizeMode = PictureBoxSizeMode.Zoom;
            byte[] img = dr.Field<byte[]>("Image");
            MemoryStream mstream = new MemoryStream(img);
            pb.Image = Image.FromStream(mstream); //ERROR IS HERE!!!!!!!!!!!!!!!!!!!!!
            pb.Name = dr.Field<string>("Name");
            pb.Parent = flowLayoutPanel1;
            pb.Click += pbClick;
            pb.BringToFront();
        }
    }

1 个答案:

答案 0 :(得分:0)

您不能将字符串与字节数组连接起来。结果将类似于'Pipe','Obstacle','System.Byte[]','97','150'

您需要使用SqlParameter。 首先创建查询,然后在命令中添加参数:

string q = "INSERT INTO dbo.Entities(Name, Type, Image, Width, Height) VALUES('Pipe','Obstacle',@image,'97','150')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("image", img);