current position:Home>In Winform development, we use several drop-down lists to display dictionary data

In Winform development, we use several drop-down lists to display dictionary data

2022-09-23 10:02:07Wu Huacong

在Winform开发中中,We are for the convenience of customers to choose,Often the system's dictionary data selection is used,After all, selection is always faster than typing、统一,Generally, we will simply encapsulate it,In order to facilitate the display and processing of the dictionary value of the control,本篇随笔介绍DevExpressSeveral common dictionary binding display methods for controls,Hope we are in practiceWInform项目中使用到.

1、Handling of regular dropdown lists

normal processing,可能会使用ComboBoxEdit A control to host a dropdown list,The value of the drop-down list can be a fixed list,It can also come from a dictionary way,具体根据实际情况而定,大概的效果如下所示.

 单击下拉列表,Some regular dictionary items are displayed,如下效果所示.

 If using the control primitive method,The way we bind the dropdown list value of the control is as follows.

combo.Properties.BeginUpdate();//可以加快
combo.Properties.Items.Clear();
combo.Properties.Items.AddRange(itemList);
combo.Properties.EndUpdate();//可以加快

However, we generally prefer efficient interface processing,Generally, extension functions of various types of interface controls are written for fast processing.

We use a separate extension file to handle different types of controls,This facilitates maintenance at the same time,It is also easy to learn from.

For example for the control above,The extension function for our binding method is shown below.

/// <summary>
/// 绑定下拉列表控件为指定的数据字典列表
/// </summary>
/// <param name="combo">下拉列表控件</param>
/// <param name="itemList">数据字典列表</param>
/// <param name="defaultValue">控件默认值</param>
/// <param name="emptyFlag">是否加入空值选项</param>
public static void BindDictItems(this ComboBoxEdit combo, List<CListItem> itemList, string defaultValue, bool emptyFlag = true)
{
    combo.Properties.BeginUpdate();//可以加快
    combo.Properties.Items.Clear();
    combo.Properties.Items.AddRange(itemList);
    if (emptyFlag)
    {
        combo.Properties.Items.Insert(0, new CListItem(""));
    }

    if (itemList.Count > 0)
    {
        if (!string.IsNullOrEmpty(defaultValue))
        {
            combo.SetComboBoxItem(defaultValue);
        }
        else
        {
            combo.SelectedIndex = 0;
        }
    }

    combo.Properties.EndUpdate();//可以加快
}

The method adds some default values ​​and the handling of whether to append blank items.

当然,In order to adapt to the binding methods of various data sources,We overloaded a lot of different function handlers,如下截图所示.

 Of course, the same can be done for other list controls of the same type.this interface,We can specify the processing operation of the call binding

private void InitDictItem()
{
    this.txtManufacture.Items.Clear();
    this.txtManufacture.Items.AddRange(DictItemUtil.GetDictByDictType("供货商"));

    this.txtBigType.Items.Clear();
    this.txtBigType.Items.AddRange(DictItemUtil.GetDictByDictType("Spare parts are classified"));
} 

或者,We can according to the type of dictionary,Let's go further and make an extension function,to simplify the binding process.

/// <summary>
/// 绑定下拉列表控件为指定的数据字典列表
/// </summary>
/// <param name="control">下拉列表控件</param>
/// <param name="dictTypeName">数据字典类型名称</param>
/// <param name="defaultValue">控件默认值</param>
/// <param name="emptyFlag">是否添加空行</param>
public static void BindDictItems(this ComboBoxEdit control, string dictTypeName, string defaultValue, bool emptyFlag = true)
{
    Dictionary<string, string> dict = BLLFactory<DictData>.Instance.GetDictByDictType(dictTypeName);
    List<CListItem> itemList = new List<CListItem>();
    foreach (string key in dict.Keys)
    {
        itemList.Add(new CListItem(key, dict[key]));
    }

    control.BindDictItems(itemList, defaultValue, emptyFlag);
}

These simplified extension functions are used,We can have a dictionary on the system,Binding is done according to the dictionary type.

private void InitDictItem()
{
    this.txtManufacture.BindDictItems("供货商");
    this.txtSearchManufacture.BindDictItems("供货商");
    this.txtSearchDept.BindDictItems("部门");
}

如上代码所示,A lot of processing is simplified,Just one function can bind the drop-down list of system dictionary type.

2、带序号的GridLookUpEdit下拉列表

有时候,We are in some common systems,It is common to see some drop-down lists with ordinal numbers,In fact, there is one insideGridControl的控件,We only need to assign the corresponding list data source,As well as setting the displayed column content,And rewrite the display processing of the serial number to achieve it.

Let's take a look at the actual effect first.

The list above is oneGridControlinner controls,我们使用这个 GridLookUpEditWhen the drop-down list control,设置好GridControlThe data source and displayed columns are basically fine.

//Bind the data source and the displayed content、隐藏值
this.txtProjectList.Properties.DataSource = list;
this.txtProjectList.Properties.ValueMember = "Value";
this.txtProjectList.Properties.DisplayMember = "Text";

//设置GridDisplayed column information
var columns = new List<LookUpColumnInfo>()
{
    new LookUpColumnInfo("Value", "显示名称")
};
for (int i = 0; i < columns.Count; i++)
{
    this.txtProjectList.Properties.View.CreateColumn(columns[i].FieldName, columns[i].Caption,
        columns[i].Width, true, UnboundColumnType.Bound, DefaultBoolean.False, FixedStyle.None);
}

//其他属性设置
this.txtProjectList.Properties.ImmediatePopup = true;
this.txtProjectList.Properties.TextEditStyle = TextEditStyles.Standard;
this.txtProjectList.Properties.PopupWidthMode = DevExpress.XtraEditors.PopupWidthMode.ContentWidth;

//Sets the width and display text of the sequence number of the list
this.txtProjectList.Properties.View.IndicatorWidth = 40;
this.txtProjectList.Properties.View.CustomDrawRowIndicator += (s, e) =>
{
    if (e.Info.IsRowIndicator && e.RowHandle >= 0)
    {
        e.Info.DisplayText = (e.RowHandle + 1).ToString();
    }
};

 Then if we need to use extension functions to simplify the actual code,So how should this be encapsulatedGridLookupEditWhat about the following controls,The extension function code we wrote is shown below.

        /// <summary>
        /// The data source of the bound control
        /// </summary>
        /// <param name="lookup">控件对象</param>
        /// <param name="dataSource">数据源</param>
        /// <param name="displayMember">显示字段</param>
        /// <param name="valueMember">值字段</param>
        /// <param name="showRowIndicator">是否显示序号</param>
        /// <param name="lookUpColumnInfos">显示的列</param>
        /// <returns></returns>
        public static object BindDictItems(this GridLookUpEdit lookup, object dataSource, string displayMember, string valueMember, bool showRowIndicator = true, params LookUpColumnInfo[] lookUpColumnInfos)
        {
            lookup.Properties.DataSource = dataSource;
            lookup.Properties.DisplayMember = displayMember;
            lookup.Properties.ValueMember = valueMember;

            lookup.Properties.View.Columns.Clear();
            for (int i = 0; i < lookUpColumnInfos.Length; i++)
            {
                lookup.Properties.View.CreateColumn(lookUpColumnInfos[i].FieldName, lookUpColumnInfos[i].Caption,
                    lookUpColumnInfos[i].Width, true, UnboundColumnType.Bound, DefaultBoolean.False, FixedStyle.None);
            }
            lookup.Properties.ImmediatePopup = true;
            lookup.Properties.TextEditStyle = TextEditStyles.Standard;

            if (showRowIndicator)
            {
                lookup.Properties.View.IndicatorWidth = 40;
                //Override serial number display,By default, no value is displayed
                lookup.Properties.View.CustomDrawRowIndicator += (s, e) =>
                {
                    if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                    {
                        e.Info.DisplayText = (e.RowHandle + 1).ToString();
                    }
                };
            }

            return dataSource;
        }

这样处理后,A lot of code has been simplified on the interface,Use code as shown below.

var list = DictItemUtil.GetDictByDictType("Spare Parts Category");
var columns = new List<LookUpColumnInfo>()
{
    new LookUpColumnInfo("Value", "显示名称")
};

this.txtProjectList2.BindDictItems(list, "Text", "Value", true, columns.ToArray());

通过上面的两种方式,We can get the data binding display methods of two common drop-down lists.

And for other similar dropdowns,as a tree list,带搜索的SearchLookupEdit等控件,We can also write custom extension functions in a similar way,This makes it very convenient for us to use.Similar to how we do it below,Do some simple encapsulation processing on them by category.

These are some of our meager experiences with the use of common controls,I hope everyone can learn from it.

copyright notice
author[Wu Huacong],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/266/202209230958319947.html

Random recommended