zoukankan      html  css  js  c++  java
  • WinForm(C#)CheckedlistBox绑定数据,并获得选中的值(ValueMember)和显示文本(DisplayMember

    本文中我将和大家讨论关于在WinForm开发中给CheckedlistBox空间绑定数据源,并获取控件中选中的所有元素的显示文本(DisplayMember)和对应的实际值(ValueMember)的问题,后者将是讨论的重点。

    为了更方便地说明,首先我要预设一些条件。

    条件预设:

    1、已定义一个DataTable对象myDataTable,并且myDataTable的字段及数据如下:

    ID 分类名称(TypeName)
    1 金属制品
    2 通用及专用机械设备
    3 纸及纸制品
    4 交通运输设备
    5 电气机械及器材
    6 通信设备
    7 计算机及其他
    8 电子设备
    9 仪器仪表及文化
    10 办公用机械

    2、WinForm状体中有一个CheckedlistBox控件,ID为:myCheckedlistBox;一个文本控件,ID为:DisplayText;两个按钮:获取已选的文本(ID:GetText),获取已选的实际值(ID:GetValue)。如下:

     image

    具体实现:

    1、给CheckedlistBox控件myCheckedlistBox绑定数据源,这个方法很简单,固定程式,网上一搜一大把,就直接上代码了

     
    1. this.myCheckedlistBox.DataSource = myDataTable;    
    2. this.myCheckedlistBox.ValueMember = "ID";    
    3. this.myCheckedlistBox.DisplayMember = "TypeName";  

    2、获取CheckedlistBox控件myCheckedlistBox中已选中的所有元素的显示文本(DisplayMember)。

     
    1. /// <summary>    
    2. /// 按钮(GetText)单击事件:获取获取已选的文本    
    3. /// </summary>    
    4. /// <param name="sender"></param>    
    5. /// <param name="e"></param>    
    6. private void GetText_Click(object sender, EventArgs e)    
    7. {    
    8.     string checkedText = string.Empty;    
    9.     for (int i = 0; i < this.myCheckedlistBox.CheckedItems.Count; i++)    
    10.     {    
    11.         checkedText += (String.IsNullOrEmpty(checkedText) ? "" : ",") + this.myCheckedlistBox.GetItemText(this.myCheckedlistBox.Items[i]);    
    12.     }    
    13.     this.DisplayText.Text = checkedText;    
    14. }   

    image

    3、获取CheckedlistBox控件myCheckedlistBox中已选中的所有元素对应的实际值(ValueMember)。

     
    1. /// <summary>    
    2. /// 按钮(GetValue)单击事件:获取已选的实际值    
    3. /// </summary>    
    4. /// <param name="sender"></param>    
    5. /// <param name="e"></param>    
    6. private void GetValue_Click(object sender, EventArgs e)    
    7. {    
    8.     string checkedText = string.Empty;    
    9.     for (int i = 0; i < this.myCheckedlistBox.Items.Count; i++)    
    10.     {    
    11.         if (this.myCheckedlistBox.GetItemChecked(i))    
    12.         {    
    13.             this.myCheckedlistBox.SetSelected(i, true);    
    14.             checkedText += (String.IsNullOrEmpty(checkedText) ? "" : ",") + this.myCheckedlistBox.SelectedValue.ToString();    
    15.         }    
    16.     }    
    17.     this.DisplayText.Text = checkedText;    
    18. }   

     image

  • 相关阅读:
    jvisualm 结合 visualGC 进行jvm监控,并分析垃圾回收
    linux 查看服务器cpu 与内存配置
    arthas 使用总结
    selinux contexts 安全上下文的临时更改
    Android 8.1 Doze模式分析(五) Doze白名单及Debug方式
    Window 任意窗口置顶软件Window TopMost Control
    Android ApkToolPlus一个可视化的跨平台 apk 分析工具
    SVN Please execute the 'Cleanup' command.
    Android 如何在64位安卓系统中使用32位SO库
    Android cmd命令查看apk是32位还是64位?
  • 原文地址:https://www.cnblogs.com/zhcw/p/2208458.html
Copyright © 2011-2022 走看看