我正在从数据库中加载名称和图像,并将它们动态添加到面板控件中。我想要的是一张图片和显示在该图片下方的名称。但是名称标签并不完全在图像下方。有没有办法添加相对于图像按钮的标签?
这是我从数据库加载图像和名称的代码:
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);
}
}
}
这是我得到的显示:
最佳答案
您的 ADO.NET 代码中存在一些不良做法。
- 始终将实现 IDisposable 的所有内容包装在 using block 中。
- 将连接范围限定为使用它们的方法。Sql Server 将处理连接池,因此请使用并处理它,不要重复使用它。
解决您的问题的方法是向您的面板添加一个新标签,然后根据您的需要设置样式。
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);
}
}
}
关于c# - 在图像按钮下动态添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838901/