0

I want this button's image use the image stored in database (image path)...

        private void button15_Click(object sender, EventArgs e)
        {
            string a = button11.Text;
            string connString = "Server=Localhost;Database=test;Uid=*****;password=*****;";
            MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand command = conn.CreateCommand();
            command.CommandText = ("Select link from testtable where ID=" + a);

            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                //button11.Image = ex.ToString();
            }

            MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                button11.Image = reader["path"].ToString();                    
            }
        } 

I think the error lies in "reader["path"].ToString();" but I don't know what syntax to use.

viperguynaz
  • 11,592
  • 4
  • 27
  • 41
Jurel Jacinto
  • 119
  • 1
  • 9

3 Answers3

0

If you stored the path to the image file on the disk in the path column, you should laod the image:

    string path = (string)reader["path"];
    button11.Image = Image.FromFile(path);

Side note: Never pass the values directly from a user input to a database query. It is vulnerable to sql injection attacks. Use parameters instead:

command.CommandText = "Select link from testtable where ID=@id";
command.Parameters.AddWithValue("@id", int.Parse(a));
Mohammad Dehghan
  • 16,319
  • 3
  • 50
  • 66
0

try this:

        while (reader.Read())
        {
            string path = reader.GetString(0);
            button11.Image = Image.FromFile(path);                    
        }
viperguynaz
  • 11,592
  • 4
  • 27
  • 41
0

Try this: ( Written right to answer box, may be there are typo! )

    private void button15_Click(object sender, EventArgs e)
    {
        string a = button11.Text;
        string imagePath;
        string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
        using(MySqlConnection conn = new MySqlConnection(connString))
        using(MySqlCommand command = conn.CreateCommand())
        {
            command.CommandText = "Select link from testtable where ID=@id";
            command.Parameters.AddWithValue("@id", int.Parse(a));

            try
            {
                conn.Open();
                imagePath= (string)command.ExecuteScalar();
            }
            catch (Exception ex)
            {
            //button11.Image = ex.ToString();
            }

            button11.Image = Image.FromFile(imagePath);
        }
    } 
Hamlet Hakobyan
  • 31,621
  • 6
  • 49
  • 65