【问题标题】:'Parameter is not valid.''参数无效。'
【发布时间】:2020-09-02 04:09:56
【问题描述】:

我正在使用 C# 开发 WinForms。我制作了一个具有方法yourvideos() 的课程视频。该方法从SQL数据库中读取数据并添加到imagelistlistview中。

首先我上传了图片,然后使用以下方法获取图片的位置:

var=open.FileName.ToString();

然后在函数uploadvideo() 中,我将图像转换为字节数组并将其插入数据库:

public void uploadvideo(string url, string path, string name,string title, DateTime date, string imgloc, string user)
{
    con.Open();
    FileStream file = new FileStream(imgloc,FileMode.Open,FileAccess.Read);
        BinaryReader br = new BinaryReader(file);
        byte[] img = br.ReadBytes((int)file.Length);
   cmd = new SqlCommand($"insert into RecipeInfo (RecipeName, [Recipe Link],Thumbnail,Username, Date, Title) values (@Name,@Path,@img,@Username,@Date,@Title)", con);
                cmd.Parameters.AddWithValue("Name", name);
                cmd.Parameters.AddWithValue("Path", path);
                cmd.Parameters.AddWithValue("Img", img);
                cmd.Parameters.AddWithValue("Username", user);
                cmd.Parameters.AddWithValue("Date", date);
                cmd.Parameters.AddWithValue("Title", title);
                cmd.ExecuteNonQuery();
}

然后是我正在检索数据的函数yourvideos()

public void yourvideos(string user, ImageList imglist, ListView list, Label l)
{
     cmd = new SqlCommand("select Title, Thumbnail from RecipeInfo where Username=@username", con);
            cmd.Parameters.AddWithValue("username", user);
    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            byte[] img = (byte[])(reader["Thumbnail"]);
            MemoryStream ms = new MemoryStream(img);
            imglist.Images.Add(Image.FromStream(ms));
            list.Items.Add(reader["Title"].ToString());
            //MessageBox.Show("Data presesnt");
        }
    }
    else
    {

        l.Visible = true;
        l.Text = "Upload videos and share your recipes with others";
    }
    reader.Close();
    con.Close();
}

该函数在按钮点击事件下的Form中调用

v1.yourvideos(Form2.setname, imageList1, yourvideoslistview, messagelabel);

当我调用 yourvideos() 时出现“参数无效”的错误 错误详情如下:

System.ArgumentException
  HResult=0x80070057
  Message=Parameter is not valid.
  Source=System.Drawing
  StackTrace:
   at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
   at System.Drawing.Image.FromStream(Stream stream)
   at loginpage.video.yourvideos(String user, ImageList imglist, ListView list, Label l) in C:\Users\maha javed\source\repos\loginpage\Recipe.cs:line 115
   at loginpage.Form3.xuiSuperButton2_Click(Object sender, EventArgs e) in C:\Users\maha javed\source\repos\loginpage\Form3.cs:line 118
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at loginpage.Program.Main() in C:\Users\maha javed\source\repos\loginpage\Program.cs:line 19

  This exception was originally thrown at this call stack:
    [External Code]
    loginpage.video.yourvideos(string, System.Windows.Forms.ImageList, System.Windows.Forms.ListView, System.Windows.Forms.Label) in Recipe.cs
    loginpage.Form3.xuiSuperButton2_Click(object, System.EventArgs) in Form3.cs
    [External Code]
    loginpage.Program.Main() in Program.cs

【问题讨论】:

  • 能否也提供异常详情?它应该给你错误行信息。
  • 尝试cmd.Parameters.AddWithValue("@Name", name);在参数名称前添加@
  • 我已编辑错误详细信息。并且使用 @ 没有区别
  • 要获取图像的字节数组,请使用byte[] imageBytes = File.ReadAllBytes(imgloc) => No Stream 和 No BinaryReader。要从该列中获取图像,var image = Image.FromStream(new MemoryStream(reader["Thumbnail"]))。当您不使用存储过程时,尽量避免使用AddWithValue()。请改用Parameters.Add()。例如,cmd.Parameters.Add(@img, SqlDbType.VarBinary).Value = imageBytes;
  • 请注意,you're still indexing your DataReader 就像 reader[5],当您只查询 2 列时。您只能拥有reader[0]reader[1]。或reader["Title"]reader["Thumbnail"]

标签: c# sql-server winforms


【解决方案1】:

来自[this page][1] 的文档。这是如何将参数添加到 SqlCommand 对象的示例:

string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored
    // in an xml column.
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.Add("@ID", SqlDbType.Int);
    command.Parameters["@ID"].Value = customerID;

    // Use AddWithValue to assign Demographics.
    // SQL Server will implicitly convert strings into XML.
    command.Parameters.AddWithValue("@demographics", demoXml);

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

}

【讨论】:

    【解决方案2】:

    在while循环中你需要调用

    while(reader.read()){
      .....
    }
    

    我建议使用 block 来处理你的 connection 、 command 和 reader 对象。

    如果图像数据的大小很大,您还可以从下面的链接中看到一些有价值的输入。

    What 'length' parameter should I pass to SqlDataReader.GetBytes()

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2011-02-03
      • 2011-05-16
      • 2013-02-16
      相关资源
      最近更新 更多