Image not showing in listview in c#

不羁岁月 提交于 2021-01-29 09:22:51

问题


I am working on Winforms where I am saving path of image in database, and then retrieving the path and giving it to Imagelist. The images from Image list are used in ImageView. But the image is not displaying, its path is correctly displayed but image is not showing.

public void yourvideos(string user, ImageList imageList, ListView lv, Label l,TextBox s)
        {
            cmd = new SqlCommand("select Title,Thumbnail from RecipeInfo where Username=@username", con);
            cmd.Parameters.AddWithValue("@username", user);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                int count = 0;
                while (reader.Read())
                {
                    s.Text = reader[1].ToString();
                    imageList.ImageSize = new Size(100, 100);
                    imageList.Images.Add("key"+count,Image.FromFile($@"{reader[1]}"));
                   
                    var listviewitem = lv.Items.Add(reader[0].ToString(), count);
                    
                    listviewitem.ImageKey = "key" + count;
                  count++;
                }
                

                
            }
            else
            {

                l.Visible = true;
                l.Text = "Upload videos and share your recipes with others";
            }
            reader.Close();
            con.Close();
        }


回答1:


This problem also occurred when I used the key, and I solved it with the Index.
You can refer to my code:

public Form1()
    {
        InitializeComponent();                
        this.listView1.View = View.LargeIcon;
       yourvideos(this.imageList1,this.listView1);
    }
    public void yourvideos( ImageList imageList1, ListView listView1)
    {
        string sql = "...";
        SqlConnection con = new SqlConnection(sql);
        SqlCommand cmd = new SqlCommand("select Title,Thumbnail from RecipeInfo", con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        int i = 0;
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                string title = reader["Title"].ToString();
                string picurl = reader["Thumbnail"].ToString();
                imageList1.ImageSize = new Size(60, 60);
                imageList1.Images.Add(Image.FromFile(picurl));
                ListViewItem item = new ListViewItem();
                item.Text = Convert.ToString(title);
                listView1.Items.Add(item);
                item.ImageIndex = i;
                i++;

            }
        }
        listView1.LargeImageList = imageList1;
        reader.Close();
        con.Close();

    }
       

Result:



来源:https://stackoverflow.com/questions/63703741/image-not-showing-in-listview-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!