EL323 EL323 - 2 months ago 37
ASP.NET (C#) Question

Dynamically adding text under image button

I am loading names & images from database and dynamically adding them to a panel control. What I want is an image and a name displayed under that image. But the name label is not exactly under the image. Is there a way to add label relative to the image button?

This is my code that loads images and names from database:

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);
}
}
}


This is what I get displayed:

enter image description here

Answer

There are some bad practices in your ADO.NET code.

  1. Always wrap everything that implements IDisposable in using blocks.
  2. Scope connections to the method they are used in. Sql Server will handle connection pooling so use it and dispose it, do not reuse it.

The fix to your question though is to add a new Label to your panel and then style it as you see fit.

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);
        }
    }
}

Please see Best Practices - Executing Sql Statements.