我遇到的一个问题开始使我感到沮丧。我使用gridviews创建了一个非常简单的博客。我还被要求能够上传图片到帖子。我遇到的问题是,如果用户创建的帖子没有图片,则无论如何图像控件都会显示带有红色x的图片。我已经尝试了多种方法,但均未成功。我正在使用自定义处理程序来获取帖子的图像。
ImageHandler.ashx
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
dr.Read()
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
catch (Exception ex)
{
return;
}
}
我确实有一个与Post表相关的Images表。如您所见,它使用QueryString并检索MessageID或Posts ID,然后显示图像。
这是我目前在Posts.aspx中用于图像控件的内容。
均价
<asp:Image ID="postImage" runat="server" ImageUrl='<%# "ImageHandler.ashx?mid="+ Eval("MessageID") %>' Width="300px" Height="300px" GenerateEmptyAlternateText="True" />
我在这里尝试过解决方案,在这里也尝试过解决方案,但对我而言没有成功。我尝试使用Visible属性,仅显示不是“空”而是相同结果的图像。如果我还有其他需要,请告诉我!
编辑:这就是我现在为ImageHandler.ashx
ImageHandler.ashx
// 1x1 transparent GIF
private readonly byte[] GifData =
{
0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
0x02, 0x44, 0x01, 0x00, 0x3b
};
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
else
{
context.Response.ContentType = "image/gif";
context.Response.Buffer = false;
context.Response.OutputStream.Write(GifData, 0, GifData.Length);
}
}
catch (Exception ex)
{
return;
}
}
我确实更新了Win给出的答案所提供的内容。唯一的问题是,gridview确实具有一种样式,即每行在白色和灰色之间交替显示颜色。因此,如果没有图像,则会出现一个白色的框,该框位于灰色的行中。
好的,所以我想出了一个解决方案。我只将一张图片保存到表格中。在插入时,它要么插入图像,要么如果没有插入图像,则插入“ NULL”。然后,我检查该表是否具有空图像,如果有,则禁用图像控件。我将以下内容放在Page_Load中。
背后的C#代码
if (Page.IsPostBack || !Page.IsPostBack)
{
foreach (GridViewRow allrows in gvPosts.Rows)
{
string messageid = ((Label)allrows.FindControl("lblMessageID")).Text;
Image image = ((Image)allrows.FindControl("postImage"));
conn.Open();
SqlCommand checkNullImage = new SqlCommand("SELECT Image FROM BlogMessages WHERE MessageID=" + messageid, conn);
nullImage = Convert.ToString(checkNullImage.ExecuteScalar());
if (nullImage == DBNull.Value.ToString())
{
image.Visible = false;
}
conn.Close();
}
这是最好的方法吗?我不确定,但是它能正常工作,并且由于我一次只显示10条帖子,因此它很快就可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句