我正在加载姓名&来自数据库的图像并将它们动态添加到面板控件中。我想要的是在该图像下显示的图像和名称。但名称标签并不完全在图像下面。有没有办法相对于图像按钮添加标签?
这是我从数据库加载图片和名称的代码:
string query1 = "SELECT photo,name FROM Artist";
using(var conn = new SqlConnection("connectionStringHere"))
using(SqlCommand cmd = new SqlCommand(query1, conn))
{
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
byte[] bytes = (byte[])reader.GetValue(0);
string strBase64 = Convert.ToBase64String(bytes);
ImageButton imgButton = new ImageButton();
imgButton.ImageUrl = "data:Image/png;base64," + strBase64;
imgButton.Width = Unit.Pixel(200);
imgButton.Height = Unit.Pixel(200);
imgButton.Style.Add("padding", "5px");
imgButton.Click += new ImageClickEventHandler(imgButton_Click);
Panel1.Controls.Add(imgButton);
Label lbl = new Label();
lbl.Text = reader.GetString(1);
lbl.CssClass = "imageLable"; // style it in your .css file
Panel1.Controls.Add(lbl);
}
}
}
这是我显示的内容:
答案 0 :(得分:3)
您的ADO.NET代码中存在一些不良做法。
您问题的解决方法是在面板中添加新标签,然后根据需要设置样式。
string query1 = "SELECT photo,name FROM Artist";
using(var conn = new SqlConnection("connectionStringHere"))
using(SqlCommand cmd = new SqlCommand(query1, conn))
{
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
byte[] bytes = (byte[])reader.GetValue(0);
string strBase64 = Convert.ToBase64String(bytes);
ImageButton imgButton = new ImageButton();
imgButton.ImageUrl = "data:Image/png;base64," + strBase64;
imgButton.Width = Unit.Pixel(200);
imgButton.Height = Unit.Pixel(200);
imgButton.Style.Add("padding", "5px");
imgButton.Click += new ImageClickEventHandler(imgButton_Click);
Panel1.Controls.Add(imgButton);
Label lbl = new Label();
lbl.Text = reader.GetString(1); // use GetString, not GetValue here
lbl.CssClass = "imageLable"; // style it in your .css file
Panel1.Controls.Add(lbl);
}
}
}
答案 1 :(得分:1)
您只需在图片按钮下添加标签:
string query1 = "SELECT photo, name FROM Artist";
SqlCommand cmd = new SqlCommand(query1, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
byte[] bytes = (byte[])reader.GetValue(0);
string strBase64 = Convert.ToBase64String(bytes);
ImageButton imgButton = new ImageButton();
imgButton.ImageUrl = "data:Image/png;base64," + strBase64;
imgButton.Width = Unit.Pixel(200);
imgButton.Height = Unit.Pixel(200);
imgButton.Style.Add("padding", "5px");
imgButton.Click += new ImageClickEventHandler(imgButton_Click);
Panel1.Controls.Add(imgButton);
Label lbl = new Label();
lbl.Text = reader.GetValue(1);
// TODO: add styling and sizing parameters here
Panel1.Controls.Add(lbl);
}
您必须为该标签添加样式,并且因为它不是图像按钮的一部分,所以它不是链接。如果您希望它可以点击,则应将ImageButton
更改为Link
,然后在Image
控件中添加Label
和Link
。