【问题标题】:Cannot convert type 'string' to 'byte[]'? [closed]无法将类型“字符串”转换为“字节 []”? [关闭]
【发布时间】:2014-12-12 16:27:19
【问题描述】:

您好,我必须在从下拉列表中选择学生 ID 时在图像框上显示学生图像。图像以二进制格式存储在 db 中。我想在不使用通用 http 处理程序的情况下显示图像。使用下面给出的代码生成一个错误。错误是“无法将类型字符串转换为字节 []”。请帮帮我。

代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataSet1TableAdapters.TextBoxTableTableAdapter tx;
    tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
    DataTable dt = new DataTable();
    dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
    foreach (DataRow row in dt.Rows)
    {
        TextBox1.Text = (row["FirstName"].ToString());
        TextBox2.Text = (row["SecondName"].ToString());  
        byte[] barrImg = (byte[])(row["StudImage"].ToString());
        string base64String = Convert.ToBase64String(barrImg , 0, barrImg.Length);
        Image1.ImageUrl = "data:image/png;base64," + base64String;
    }
}

SQL 查询:

SELECT FirstName, SecondName, StudentImage FROM TextBoxTable WHERE (Id = @Id)

aspx来源:

<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" />
</div>

数据库:

【问题讨论】:

  • 错误信息说明了一切,您不能将字符串转换为字节数组。

标签: c# image binary


【解决方案1】:

是的,问题就在这里:

byte[] barrImg = (byte[])(row["StudImage"].ToString());

您在row["StudImage"] 上致电ToString()。这将导致String。然后,您将该字符串转换为 byte[] - 但这不起作用,因为没有这样的转换。 (你希望它做什么?)

根本不清楚你为什么要调用ToString - 如果值是二进制数据,我希望它可以工作:

byte[] barrImg = (byte[]) row["StudImage"];

请注意,您无需向 Convert.ToBase64String 提供三个参数 - 您可以使用:

string base64 = Convert.ToBase64String(barrImg);

我个人建议您也对之前的语句使用强制转换 - 如果值 不是 字符串,那么这可能是一个严重的问题:

TextBox1.Text = (string) row["FirstName"];
TextBox2.Text = (string) row["SecondName"];  

另一方面,您的架构允许空值 - 目前您根本没有考虑到这一点。如果值是实际上 DbNull.Value,上述所有转换都会抛出异常。您应该单独考虑如何处理。

【讨论】:

  • tnx @jon,我想要,除了这个答案没有任何帮助
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多