c# - 在图像按钮下动态添加文本

标签 c# asp.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); 
            lbl.CssClass = "imageLable"; // style it in your .css file
            Panel1.Controls.Add(lbl);
        }
    }
}

这是我得到的显示:

enter image description here

最佳答案

您的 ADO.NET 代码中存在一些不良做法。

  1. 始终将实现 IDisposable 的所有内容包装在 using block 中。
  2. 将连接范围限定为使用它们的方法。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/

相关文章:

c# - 远程服务器返回错误 : (403) Forbidden

c# - MySQL 连接器 v.6.3.6 .NET 中 GUID 类型的问题

c# - 字符串函数(正则表达式?)从 url 字符串中删除查询字符串对

c# - 访问匿名类型集合中的属性 - C#

asp.net - User.Identity.GetUserId() 方法在 Web Api 2 Controller 中不起作用

c# - 在 C# 中为同步/异步任务添加重试/回滚机制的最佳方法是什么?

c# - 使用前是否应检查 .NET EF Core DbContext 属性为 null

c# - 使用 iTextSharp 从 PDF 中提取附加元数据

c# - 工厂模式、另一种模式还是根本没有模式?

c# - 如何在c#中执行命令?