2013-06-26 58 views
1

在我的网站中,我有2张表 - 专辑和图像。如何在运行时在C#中添加<span>标签

album contains aid,alname。同样图像包含 - imgid,imgname, imgurl,imgdes和aid [外键]。

这是我的gallery.aspx页:

<body style="background-image:url('Images/Backgrounds/back.jpg')"> 
    <form id="form1" runat="server"> 
     <h1 style="color:White"><i>Gallery - Albums</i></h1> 
     <div id="container" runat="server" style="border-style:ridge; border-color:dimgrey; height:565px; padding-left:50px;padding-right:30px;padding-top:20px;padding-bottom:20px;"></div> 
    </form> 
</body> 

,这是我的代码隐藏:在图像按钮

con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 
con.Open(); 
com = new SqlCommand("select * from album", con); 
reader = com.ExecuteReader(); 

DataTable dtnew = new DataTable(); 
dtnew.Load(reader); 
DataTable[] dt = new DataTable[6]; 
con.Close(); 
if (dtnew.Rows.Count > 0) 
{ 
    for (int i = 0; i < dtnew.Rows.Count; i++) 
    { 
     con.Open(); 

     int id = Convert.ToInt32(dtnew.Rows[i]["aid"]); 
     DataTable dttemp = new DataTable(); 
     SqlCommand com1 = new SqlCommand("select * from image where aid=" + id + " ORDER BY aid desc", con); 
     SqlDataReader dr = com1.ExecuteReader(); 
     dttemp.Load(dr); 
     dt[i] = dttemp; 
     ImageButton img = new ImageButton(); 
     img.ImageUrl = Convert.ToString(dt[i].Rows[0]["imgurl"]); 
     img.ID = Convert.ToString(dtnew.Rows[i]["aid"]); 
     img.Click += new ImageClickEventHandler(Img1_Click); 
     img.AlternateText = Convert.ToString(dtnew.Rows[i]["alname"]); 
     img.ToolTip = Convert.ToString(dtnew.Rows[i]["alname"]); 
     img.CssClass = "galimg"; 

     con.Close(); 

     container.Controls.Add(img); 
    } 
} 

此代码仅加载1图像并将其显示为相册,当点击时,它将加载另一个页面,其中所有与该相册有关的图像。

这是现在的样子:

enter image description here

我现在想的是我绝对要非常久远的循环每个ImageButton的添加SPAN或DIV的部分。所以这个图像按钮将有一些背景的宽度和高度大于图像按钮..我怎么能做到这一点。

我该如何在运行时做到这一点?

回答

1

您可以将您的ImageButton添加到HtmlGenericControl - 所以只是每个按钮之前,您可以创建一个新的HTML控件,然后将您的按钮添加到它并将其添加到您的页面。

HtmlGenericControl类的构造函数需要你的HTML控件的标签名,所以很容易把它从spandiv改变 - 只是通过"div"在代替。

您可以使用此HtmlGenericControl类创建任何您喜欢的html元素。

所以......这样的事情:

HtmlGenericControl s = new HtmlGenericControl("span"); 
s.Attributes.Add("class", "myCssClass"); 
s.Attributes.Add("id", "myUniqueIdButNotNeeded"); 
// then your button as normal 
ImageButton img = new ImageButton(); 
// rest of your button code... 

// add button to span 
s.Controls.Add(img); 

// add the span 
container.Controls.Add(s); 
+0

给我一秒钟.. I'l尝试.. 。:) –

+0

哇兄弟...作品完美...正如所料...非常感谢... :) +1 –

+1

非常欢迎:) – Darren