简体   繁体   中英

Programmatically setting button image from database

This is my first time posting a question here and would really like for someone to help me.

I have a select statement that retrieves data from each row in a ProductsTable in my database and creates a button from it. Each row from the table has an image and I would like to assign that image as the buttons icon. Everything else works fine. eg the button is successfully created with its label and price BUT the image bit is not working. This my code for retrieving and creating the buttons.

 try
 {
     string sqlQuery2 = @"SELECT tp.Description AS [Description], tcpf.Frequency AS [Frequency], 
                         tcpf.Price AS [Price]
                         FROM tblCustProdFreq tcpf 
                         INNER JOIN tblProduct tp ON tp.ProductID = tcpf.ProductID 
                         WHERE tcpf.CustomerID = " + custID +
                         "ORDER BY tp.Description";

     using (SqlCommand comm = new SqlCommand(sqlQuery2, DatabaseConnectionClass.conn))
     {
         using (SqlDataReader reader = comm.ExecuteReader())
         {
             while (reader.Read())
             {
                 Button newBtn = new Button();

                 newBtn.FlatStyle = FlatStyle.Popup;
                 newBtn.Text = reader["Description"].ToString();
                 newBtn.Tag = reader["Price"].ToString();
                 newBtn.Size = new System.Drawing.Size(70, 40);
                 newBtn.Click += new EventHandler(newBtn_Click);

                 flowLayoutPanel1.Controls.Add(newBtn);

Can anyone help me complete the code so that it assigns an image to the button...(I have purposely not included image in the SELECT statement)

You need to get the binary data out first then "convert it" to an image:

 byte[] data = (byte[])reader["YourColumnName"];
 using (MemoryStream ms = new MemoryStream(data))
 {
     //here you get the image and assign it to the button.
     Image image = new Bitmap(ms);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM