如何根据用户输入的值创建多个div

时间:2012-11-25 21:47:42

标签: c# javascript asp.net html

我正在开发一个asp.net项目,其中涉及的主要任务是在按钮点击时生成图像div。 就像从数据库中检索图像并在屏幕上显示它(另一个div或表)。 如何完成这项任务? 我很高兴知道如何在按钮点击上放置图像然后在下一个按钮上单击下一个图像应该出现在它旁边。

1 个答案:

答案 0 :(得分: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);