您可以使用处理程序在 gridview 中显示图像,您的 html 标记看起来像里面
Gridview ItemTemplate
将图像控件 src 设置为src=~/ShowImage.ashx?id=" + id
ShowImage.ashx
返回 MemoryStream((byte[])img); 的处理程序在哪里?
在您的情况下,您的查询字符串是characterID
所以你的图像 src 将是 src=~/ShowImage.ashx?id=" + characterID
更新答案:
html标记:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="CharacterID">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Bind("characterID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GameLevel">
<ItemTemplate>
<asp:Label ID="lblglevel" runat="server" Text='<%# Bind("gameLevel") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#"ShowImage.ashx?getID="+Eval("characterID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后面的代码:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = getData();
GridView1.DataSource = dt;
GridView1.DataBind();
}
public DataTable getData()
{
SqlDataAdapter dap = new SqlDataAdapter("select characterID,blueBallImage,gameLevel from CorrespondingBall", cn);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];
}
通用处理程序:在此处添加新的通用处理程序 showIamges.ashx 是我的通用处理程序
public void ProcessRequest(HttpContext context)
{
Int32 my_Id;
if (context.Request.QueryString["getID"] != null)
{
my_Id = Convert.ToInt32(context.Request.QueryString["getID"]);
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(my_Id);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
}
public Stream ShowEmpImage(int my_Id)
{
string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "select blueBallImage from CorrespondingBall WHERE characterID = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", my_Id);
connection.Open();
object img = cmd.ExecuteScalar();
return new MemoryStream((byte[])img);
}