0

我正在 VS 2010 C# 中开发一个 winform 应用程序。我开发了一个表单来插入和更新用户详细信息。

我的更新用户表单如下图

![更新用户画面][1]

http://i.stack.imgur.com/iZaAJ.png

更新的编码是

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using System.IO;

namespace SampleApplication
{
public partial class UserUpdate : Form
{
    public UserUpdate()
    {
        InitializeComponent();
    }
    SqlDataAdapter da;
    SqlConnection con = new SqlConnection("user id=sa; password=123;initial     catalog=Inventory;data source=Aniket-PC");
    SqlCommand cmd;
    MemoryStream ms;
    byte[] photo_array;
    DataSet ds;
    int rno = 0;
    string str;
    private void nameTxt_Validating(object sender, CancelEventArgs e)
    {
        if (nameTxt.Text.Trim().Length == 0)
        {
            namewarning.Visible = true;
        }
        else
        {
            namewarning.Visible = false;
        }
    }

    private void Update_Load(object sender, EventArgs e)
    {
        contTxt.MaxLength = 10;
        retriveData();
        retriveImg();
    }
    void retriveImg()
    {
        con.Open();
        cmd = new SqlCommand("Select Logo from Register where UserName='" + uNameTxt.Text + "'", con);
        da = new SqlDataAdapter(cmd);
        ds = new DataSet("MyImage");
        da.Fill(ds, "MyImage");
        DataRow myRow;
        myRow = ds.Tables["MyImage"].Rows[0];
        photo_array = (byte[])myRow["Logo"];
        ms = new MemoryStream(photo_array);
        profPic.Image = Image.FromStream(ms);
        con.Close();
    }

    void retriveData()
    {
        con.Open();
        cmd = new SqlCommand("Select * from Register where UserName='"+uNameTxt.Text+"'",con);
        SqlDataReader read = cmd.ExecuteReader();
        while (read.Read())
        {
            nameTxt.Text = (read["Name"].ToString());
            passTxt.Text = (read["Password"].ToString());
            conPassTxt.Text = (read["Password"].ToString());
            emailTxt.Text = (read["EmailId"].ToString());
            addTxt.Text = (read["Address"].ToString());
            contTxt.Text = (read["ContactNo"].ToString());
            DORTxt.Text = (read["DOR"].ToString());
            validity.Text = "Account Valid till "+(read["Validity"].ToString());
        }
        read.Close();
        con.Close();            
    }

    private void AttachBtn_Click(object sender, EventArgs e)
    {
        // Open  image by OpenFiledialog and show it in PicturBox.
        try
        {
            //filter only image format files.
            openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
            DialogResult res = openFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                Image img = new Bitmap(openFileDialog1.FileName);

                //inserting image in PicturBox
                profPic.Image = img.GetThumbnailImage(127, 128, null, new IntPtr());
                openFileDialog1.RestoreDirectory = true;
            }
        }
        catch
        {
            MessageBox.Show("Cannot upload image");
        }
    }
    private void UpdateBtn_Click_1(object sender, EventArgs e)
    {
        string DOM = dateTimePicker1.Value.ToShortDateString();
        if (namewarning.Visible == true || picError.Visible == true || PassError.Visible == true || emailwarningImg.Visible == true)
        {
            MessageBox.Show("Please correct the marked fields");
        }
        else
        {
            //cmd = new SqlCommand("update Register set (Name,Password,EmailId,Address,ContactNo,Logo,DOM) values('" + nameTxt.Text.Trim() + "','" + passTxt.Text.Trim() + "','" + emailTxt.Text.Trim() + "','" + addTxt.Text.Trim() + "','" + contTxt.Text.Trim() + "',@Logo,'"  + DOM+ "')", con);
            str = string.Format("update Register set Name='{0}', Password='{1}',EmailID='{2}',Address='{3}',ContactNo='{4}',Logo='{5}',DOU='{6}' where UserName='{7}'", nameTxt.Text.Trim(), passTxt.Text.Trim(), emailTxt.Text.Trim(),addTxt.Text.Trim(), contTxt.Text.Trim(), @"Logo" ,DOM,uNameTxt.Text);
            con_photo();
            //con.Open();
            cmd = new SqlCommand(str, con);
            int count= cmd.ExecuteNonQuery();
            if (count > 0)
                MessageBox.Show("Sucsess");
            else
                MessageBox.Show("need to work");
        }
    }
    void con_photo()
    {
        if (profPic.Image != null)
        {
            ms = new MemoryStream();
            profPic.Image.Save(ms, ImageFormat.Jpeg);
            byte[] photo_array = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo_array, 0, photo_array.Length);
            cmd.Parameters.AddWithValue("@Logo", photo_array);
        }
    }

当我运行应用程序时,它执行得很好并显示成功消息但是当我再次尝试查看更新用户表单时,它显示在屏幕截图错误下方

http://i.stack.imgur.com/7z1Rx.png

在检索Img ()

请帮我解决这个问题..

4

3 回答 3

0

也许我错了,但我会尝试这样做

photo_array = (byte[])myRow["Logo"];
if photo_array.length.trim()>0
{
    ms = new MemoryStream(photo_array);  
    profPic.Image = Image.FromStream(ms);

}
con.Close();

当字符串的长度为 0 时可能会出现此错误

另一件事是您没有将图像保存在数据库中

于 2013-10-17T11:03:38.277 回答
0

您没有将图像字节传递给UPDATE命令,而是一个包含单词的字符串Logo

另外:避免使用字符串连接或String.Format. 改用参数化查询!


另外:不要使用NVARCHAR字段来存储图像字节(除非您先从它们创建 BASE64 字符串),而是使用VARBINARYorIMAGE列。


问题出在以下行:

str = string.Format("update Register set ... ,Logo='{5}' ...", ..., @"Logo", ...);

如您所见,您正在格式化一个字符串,但您插入的不是图像中的字节,而是单词“Logo”。

假设该列Logo的类型是IMAGEor VARBINARY,我会这样写:

byte[] photo_array = null;

if (profPic.Image != null)
{
    MemoryStream ms = new MemoryStream();
    profPic.Image.Save(ms, ImageFormat.Jpeg);

    photo_array = ms.GetBuffer();
}

if (photo_array != null)
{
    SqlCommand cmd = new SqlCommand("UPDATE Register SET Logo=@logo", connection);
    cmd.Parameters.AddWithValue("@logo", imageBytes);
    cmd.ExecuteNonQuery();
}
于 2013-10-17T11:01:14.977 回答
-1

//C#代码

SqlCommand cmdSelect = new SqlCommand("从 ID=1 的表中选择 ImageValue", ObjCon); ObjCon.Open();

        byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
        ObjCon.Close();
         string strfn = Convert.ToString(DateTime.Now.ToFileTime());
        FileStream fs = new FileStream("C:\\Temp\\1.txt", FileMode.CreateNew, FileAccess.Write);
        fs.Write(barrImg, 0, barrImg.Length);
        fs.Flush();
        fs.Close();

// 1.txt 文件将在 c:\temp 文件夹中创建

于 2015-02-27T15:51:08.763 回答