C# 将图像和字符串添加到组合框中

C# 将图像和字符串添加到组合框中,c#,winforms,combobox,drawimage,C#,Winforms,Combobox,Drawimage,在回顾了所有相关主题之后,仍然无法找到一个合适的答案来全面说明我们是如何做到这一点的。(此处使用Winforms,而不是WPF) 我从两个不同的数据表列填充一个组合框,引用一个用户列表和一个用户组列表。当组合框打开时,两列成为一个列表。我想有两个图像(或图标),一个代表一个用户项目,另一个代表一个用户组。希望在文本之前显示图像(文本是从数据表中提取的名称) 我意识到,如果没有进一步的代码,我不能简单地混合和匹配两种不同的对象类型,即字符串和图像,但下面的示例,用外行的话说,就是我想要实现的。有人

在回顾了所有相关主题之后,仍然无法找到一个合适的答案来全面说明我们是如何做到这一点的。(此处使用Winforms,而不是WPF)

我从两个不同的数据表列填充一个组合框,引用一个用户列表和一个用户组列表。当组合框打开时,两列成为一个列表。我想有两个图像(或图标),一个代表一个用户项目,另一个代表一个用户组。希望在文本之前显示图像(文本是从数据表中提取的名称)

我意识到,如果没有进一步的代码,我不能简单地混合和匹配两种不同的对象类型,即字符串和图像,但下面的示例,用外行的话说,就是我想要实现的。有人能给我建议吗

 private void AddUsersGroupsComboboxPopulate()
    {
        // Clear the comobox before re-populating.
        AddUserGroupCombobox.Items.Clear();

        // Fill the combobox with a list of the User Groups names.
        for (int i = 0; i < DB_UserGroups.userGroupsDataTable.Rows.Count; i++)
        {
            AddUserGroupCombobox.Items.Add(Image1 + DB_UserGroups.userGroupsDataTable.Rows[i]["UserGroup"]);

        }
        // Fill the combobox with a list of the User Account names.
        for (int i = 0; i < DB_Users.userAccountsDataTable.Rows.Count; i++)
        {
            AddUserGroupCombobox.Items.Add(Image2 + DB_Users.userAccountsDataTable.Rows[i]["Username"]);
        }
    }
private void addUsersGroupsComboxPopulate()
{
//重新填充之前,请清除此框。
AddUserGroupCombobox.Items.Clear();
//用用户组名称列表填充组合框。
对于(int i=0;i
好的,经过16小时的挠头,我终于把它钉住了

解决方案概述:

我的应用程序包含一个Windows窗体(不是WPF),用于创建电子邮件用户和组,以通知软件中的事件。我创建了一个组合框,它从两个不同的数据表源(一个是用户组,另一个是用户帐户)中提取项目,其目的是管理员可以创建电子邮件收件人用户和组

我真正需要解决的部分是配置组合框,以允许在组合框列表中显示图标(导入的图像)和文本。挑战的一部分是让我的头绕过owner draw属性,并纯粹通过作为自定义实体的代码创建布局。我在网上找不到任何完整的例子,所以不得不四处冲浪,经过大量的尝试和错误,我最终达到了目的

我在下面的代码中添加了大量注释,希望其他人能从我今天经历的痛苦中受益!。我的环境可能更为定制,但花一点时间检查代码,您很快就会了解我的想法。希望这有帮助:)

使用系统;
使用System.Collections.Generic;
使用系统图;
使用System.Windows.Forms;
私有无效通知表单加载(对象发送方,事件参数e)
{
PopulateUsersGroupsList();//用于在窗体打开时创建用户组和用户帐户的列表。
日志信息(“通知表单已打开”);
}
//创建用于组合框图标的图像列表
只读静态ImageList ImageListMailRecipients=新建ImageList();
//创建一个列表,用于存储两个不同数据表中的用户帐户和用户组名称。
公共静态只读列表emailRecipientsUserList=新列表();
/// 
///此方法用于创建一个列表,以保存从两个不同数据表中提取的值。
///提取的信息为列表提供了用户组和用户帐户的名称。
///注意:当Windows窗体关闭时,关闭方法将运行命令“emailRecipientsUserList.Clear()
///以确保列表已清除,并且不会继续累积每个条目
///打开表单的时间。
/// 
私有void PopulateUsersGroupsList()
{
//将这两个图像添加到图像列表中,图像将从properties resources文件夹中加载。
//这些图像将作为图标显示在组合框中。
imageListMailRecipients.Images.Add((Image)(新位图(Properties.Resources.UserGroup2));
imageListMailRecipients.Images.Add((Image)(新位图(Properties.Resources.UserAccount));
//将默认字符串添加到组合框默认值的列表中,提示用户进行选择
//在启动之前,打开下拉组合框。
emailRecipientsUserList.Add(新的KeyValuePair(“,”--Select--”);
//将数据表中的每个用户组添加到列表中。使用KeyValuePairs可以区分
//在用户组列表和用户帐户列表之间。
对于(int i=0;i using System;
 using System.Collections.Generic;
 using System.Drawing;
 using System.Windows.Forms;

 private void NotificationsForm_Load(object sender, EventArgs e)
    {
        PopulateUsersGroupsList(); // Used to create the list of User Groups & User Accounts when the form opens.

        log.Info("NotificationsForm Opened");
    }

    // Create an image list that will be used for the combobox icons
    readonly static ImageList imageListEmailRecipients = new ImageList();

    // Create an List that will be used to store the user account and user group names from the two different data tables.
    public static readonly List<KeyValuePair<string, string>> emailRecipientsUserList = new List<KeyValuePair<string, string>>();

    /// <summary>
    /// This method is used to create a list to hold the values pulled from two different data tables.
    /// The information pulled provides the list with the names of the User Groups & User Accounts.
    /// Note: When the Windows Form closes, the closing method runs the command 'emailRecipientsUserList.Clear()'
    /// in order to ensure that the list is cleared and does not continue to build up with dulicate entries each
    /// time the form is opened.
    /// </summary>
    private void PopulateUsersGroupsList()
    {
        // Add the two images to the image list, images are loaded from the properties resources folder.
        // These images will be used as icons to display in the combobox.
        imageListEmailRecipients.Images.Add((Image)(new Bitmap(Properties.Resources.UserGroup2)));
        imageListEmailRecipients.Images.Add((Image)(new Bitmap(Properties.Resources.UserAccount)));

        // Add a default string to the list for the combobox default value, prompting the user to make their selection
        // before the open up the dropdown combobox.
        emailRecipientsUserList.Add(new KeyValuePair<string, string>("", "--Select--"));

        // Add each User Group from the data table to the list. KeyValuePairs are used so we can differentiate
        // between the User Groups list and User Accounts list.
        for (int i = 0; i < DB_UserGroups.userGroupsDataTable.Rows.Count; i++)
        {
            emailRecipientsUserList.Add(new KeyValuePair<string, string>("UserGroup", DB_UserGroups.userGroupsDataTable.Rows[i]["UserGroup"].ToString()));
        }

        // Add each User Account from the data table to the list. KeyValuePairs are used so we can differentiate
        // between the User Groups list and User Accounts list.
        for (int i = 0; i < DB_Users.userAccountsDataTable.Rows.Count; i++)
        {
            //emailRecipientsUserList.Add(DB_Users.userAccountsDataTable.Rows[i]["Username"].ToString());
            emailRecipientsUserList.Add(new KeyValuePair<string, string>("Username", DB_Users.userAccountsDataTable.Rows[i]["Username"].ToString()));
        }
        // Run the method below that will populate the combobox with the User Groups & User Accounts from the list.
        AddUsersGroupsComboboxPopulate();
    }

    /// <summary>
    /// Method used to populate the combobox using the 'emailRecipientsUserList' created from the method above. 
    /// </summary>
    private void AddUsersGroupsComboboxPopulate()
    {
        // Clear the comobox before re-populating.
        AddUserGroupCombobox.Items.Clear();

        // Map the combobox's data source to the 'emailRecipientsUserList' source.
        this.AddUserGroupCombobox.DataSource = emailRecipientsUserList;
        // Confirure the combobox to the show the 'Value' portion ONLY from the KeyValuePair 
        // value set found in the 'emailRecipientsUserList'.
        this.AddUserGroupCombobox.DisplayMember = "Value";
        // Configure the combobox to utilise the Key from the 'emailRecipientsUserList' as its member value.
        this.AddUserGroupCombobox.ValueMember = "Key";

        // Set the combobox to owner draw mode - otherwise you cannot change the output style to your own format.
        AddUserGroupCombobox.DrawMode = DrawMode.OwnerDrawFixed;
        // Instruct the combobox to draw itself using the 'AddUserGroupCombobox_DrawItem' method below.
        AddUserGroupCombobox.DrawItem += AddUserGroupCombobox_DrawItem;
        // Set the default height for each of the items displayed in the combobox.
        AddUserGroupCombobox.ItemHeight = 20;
    }

    // Mouse index used to reference the position of the cursor when navigating up and down the combobox list.
    private readonly int _MouseIndex = -1;

    /// <summary>
    /// This method is used to draw the items from the 'emailRecipientsUserList' into the combobox, 
    /// using an owner draw custom format so we can show the the User Group & User
    /// Account icons adjacent their relevant names in the combobox list.
    /// 
    /// In the method above, we created the 'emailRecipientsUserList' that contains data columns
    /// from two different data tables, the first datatable holds the names of the User Groups and the second
    /// holds the User Accounts. We're utilizing the KeyValuePair in order to provide a
    /// means of applying some logic to the population of our combobox in order to differentiate 
    /// between a User Group and a User Account. This allows us to dynamically
    /// assign the relevant icon display, adjacent each of the items in the combobox list.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void AddUserGroupCombobox_DrawItem(object sender, DrawItemEventArgs e)
    {
        // Set the textBrush color to Windows Text.
        Brush textBrush = SystemBrushes.WindowText;

        if (e.Index > -1)
        {
            // Highlight the combobox item when the mouse cursor hovers over the item in the dropdown list.
            if (e.Index == _MouseIndex)
            {
                e.Graphics.FillRectangle(SystemBrushes.HotTrack, e.Bounds);
                textBrush = SystemBrushes.HighlightText;
            }
            else
            {
                // Highlight the combobox item when slected in the dropdown list.
                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                {
                    e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
                    textBrush = SystemBrushes.HighlightText;
                }
                else
                {
                    // Restore background colour to deafult when the mouse leaves the item.
                    e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
                }
            }
            // Draw the string i.e populate the combobox with the list of the text names
            // for the User groups & User Accounts
            e.Graphics.DrawString(emailRecipientsUserList[e.Index].Value.ToString(), e.Font, textBrush, e.Bounds.Left + 20, e.Bounds.Top);

            // IF Statements below are used to determine which icon to display in the drop down list, depending on
            // whether the comboxo item is a User Group or User Account name.
            if (emailRecipientsUserList[e.Index].Key == "UserGroup")
            {
                // Image list index '0' represents the icon image for the User Group.
                e.Graphics.DrawImage(imageListEmailRecipients.Images[0], e.Bounds.Left, e.Bounds.Top);
            }

            if (emailRecipientsUserList[e.Index].Key == "Username")
            {
                // Image list index '0' represents the icon image for the User Account.
                e.Graphics.DrawImage(imageListEmailRecipients.Images[1], e.Bounds.Left, e.Bounds.Top);
            }
        }
    }