2012-11-25 110 views
0

我正在研究一个asp.net项目,涉及的主要任务是在按钮单击时生成图像div。 如从数据库检索图像并在屏幕上显示(另一个div或表格)。 这项任务如何完成? 我会很高兴知道如何将图像放在按钮单击上,然后在下一个按钮上点击下一个图像。如何根据用户输入的值创建多个div

回答

0

通过下面的代码就可以生成动态的div:

HtmlGenericControl div1 = new HtmlGenericControl("div"); 

现在你想显示从数据库使用的处理程序,如下面的图像。创建一个ashx文件,添加代码,然后动态获取图像控件,并将图像处理程序的输出绑定到图像的imageURl属性。该代码是:

<%@ WebHandler Language="C#" Class="DisplayImg" %> 

using System; 
using System.Web; 
using System.Configuration; 
using System.IO; 
using System.Data; 
using System.Data.SqlClient; 

public class DisplayImg : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     string theID; 
     if (context.Request.QueryString["id"] != null) 
      theID = context.Request.QueryString["id"].ToString(); 
     else 
      throw new ArgumentException("No parameter specified"); 

     context.Response.ContentType = "image/jpeg"; 
     Stream strm = DisplayImage(theID); 
     byte[] buffer = new byte[2048]; 
     int byteSeq = strm.Read(buffer, 0, 2048); 

     while (byteSeq > 0) 
     { 
      context.Response.OutputStream.Write(buffer, 0, byteSeq); 
      byteSeq = strm.Read(buffer, 0, 2048); 
     } 
    } 

    public Stream DisplayImage(string theID) 
    { 
     SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString()); 
     string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID"; 
     SqlCommand cmd = new SqlCommand(sql, connection); 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.AddWithValue("@ID", theID); 
     connection.Open(); 
     object theImg = cmd.ExecuteScalar(); 
     try 
     { 
      return new MemoryStream((byte[])theImg); 
     } 
     catch 
     { 
      return null; 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

只需添加一行在CS代码

UploadImg.ImageUrl = "~/DisplayImg.ashx?id=" + code; 

终于在div中添加图像

div1.Controls.Add(YOUR IMAGE's ID); 
相关问题