嗨我必须在图像框中显示学生图像,同时从下拉列表中选择学生ID.图像以db2中的二进制格式存储.我想在不使用通用http处理程序的情况下显示图像.使用下面给出的代码生成一个错误.错误是"无法将类型字符串转换为byte []".请帮我.
码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
SQL查询:
SELECT FirstName, SecondName, StudentImage FROM TextBoxTable WHERE (Id = @Id)
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
数据库:

是的,问题出在这里:
byte[] barrImg = (byte[])(row["StudImage"].ToString());
Run Code Online (Sandbox Code Playgroud)
你打电话ToString()的row["StudImage"].这将导致一个String.然后你将该字符串转换为byte[]- 但这不起作用,因为没有这样的转换.(你期望它做什么?)
目前还不清楚你为什么要打电话ToString- 如果值是二进制数据,我希望这可行:
byte[] barrImg = (byte[]) row["StudImage"];
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要提供三个参数Convert.ToBase64String- 您可以使用:
string base64 = Convert.ToBase64String(barrImg);
Run Code Online (Sandbox Code Playgroud)
我个人鼓励你也为你早先的陈述使用强制转换 - 如果值不是字符串,那么可能代表一个严重的问题:
TextBox1.Text = (string) row["FirstName"];
TextBox2.Text = (string) row["SecondName"];
Run Code Online (Sandbox Code Playgroud)
另一方面,您的架构允许空值 - 目前您根本没有考虑这些值.如果值实际上 是上面的所有转换将抛出异常DbNull.Value.作为一个单独的问题,您应该考虑如何处理它.