将名称从数据库的图像检索到ListView

时间:2019-04-23 08:36:37

标签: c# sql-server

我正在创建一个桌面聊天应用程序,用户可以在其中通过名称或电子邮件搜索其他用户。 当我搜索其他用户时,他们的图像不是按顺序排列的。

//这是主页表格中的代码

    private void BtnSearch_Click(object sender, EventArgs e)
    {
        if (Friends.SelectedIndex == 0)
        {
            UsersClass.SearchContacts(listAllContacts, ImgListAllContacts, TxtSearch.Text.Trim());
        }
    }

//这是来自UserClass的代码

    public static void SearchContacts(ListView listview, ImageList imagelist, string searchkey)
    {
        DataTable dt = new DataTable();
        listview.Items.Clear();
        ListViewItem[] listviewitem = null;
        dt = DataBaseAccess.Retrive("select UID,FullName,DP from TKDBUsers WHERE ( FullName+' '+UserName ) Like '%" + searchkey + "%' AND UID != '" + LogInUser.UID + "'");
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                listviewitem = new ListViewItem[(dt.Rows.Count)];
                int LC = 0;        //List contacts
                foreach (DataRow item in dt.Rows)
                {
                    Image img = DataBaseAccess.Base64ToImage(Convert.ToString(item["DP"]));
                    imagelist.Images.Add(img);
                    listviewitem[LC] = new ListViewItem(new string[] { Convert.ToString(item["UID"]) + " - " + Convert.ToString(item["FullName"]) }, LC);
                    LC++;
                }
            }
        }
        if (listviewitem != null)
        {
            listview.Items.AddRange(listviewitem);
        }

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

您不需要清除图像列表吗?

答案 1 :(得分:0)

尝试将选择查询更改为(添加“ ORDER BY UserName”):

dt = DataBaseAccess.Retrive("
    SELECT UID, FullName, DP 
    FROM TKDBUsers 
    WHERE (FullName+' '+UserName ) LIKE '%" + searchkey + "%' 
    AND UID != '" + LogInUser.UID + "' 
    ORDER BY UserName");