csharp:A Custom CheckedListBox with Datasource



from A Custom CheckedListBox with Datasource  http://www.codeproject.com/Articles/22960/A-Custom-CheckedListBox-with-Datasource-Implementa

 /// <summary>
    /// (eraghi)
    /// Custom CheckedListBox with binding facilities (Value property)
    /// from A Custom CheckedListBox with Datasource  http://www.codeproject.com/Articles/22960/A-Custom-CheckedListBox-with-Datasource-Implementa
    /// </summary>
    [ToolboxBitmap(typeof(CheckedListBox))]
    public class DuCheckedListBox : CheckedListBox
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public DuCheckedListBox()
        {
            this.CheckOnClick = true;

        }

        /// <summary>
        ///    Gets or sets the property to display for this CustomControls.CheckedListBox.
        ///
        /// Returns:
        ///     A System.String specifying the name of an object property that is contained
        ///     in the collection specified by the CustomControls.CheckedListBox.DataSource
        ///     property. The default is an empty string ("").
        /// </summary>
        [DefaultValue("")]
        [TypeConverter("System.Windows.Forms.Design.DataMemberFieldConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3de65a4a-2b5f-4d9d-88de-bfb692b10f93")]
        [Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3de65a4a-2b5f-4d9d-88de-bfb692b10f93", typeof(UITypeEditor))]
        [Browsable(true)]
        public new string DisplayMember
        {
            get
            {
                return base.DisplayMember;
            }
            set
            {
                base.DisplayMember = value;

            }
        }

        /// <summary>
        ///    Gets or sets the property to get the values for this CustomControls.CheckedListBox.
        ///
        /// Returns:
        ///     A System.String specifying the name of an object property that is contained
        ///     in the collection specified by the CustomControls.CheckedListBox.DataSource
        ///     property. The default is an empty string ("").
        /// </summary>
        [DefaultValue("")]
        [TypeConverter("System.Windows.Forms.Design.DataMemberFieldConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3de65a4a-2b5f-4d9d-88de-bfb692b10f93")]
        [Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3de65a4a-2b5f-4d9d-88de-bfb692b10f93", typeof(UITypeEditor))]
        [Browsable(true)]
        public new string ValueMember
        {
            get
            {
                return base.ValueMember;
            }
            set
            {
                base.ValueMember = value;

            }
        }

        /// <summary>
        /// Gets or sets the data source for this CustomControls.CheckedListBox.
        /// Returns:
        ///    An object that implements the System.Collections.IList or System.ComponentModel.IListSource
        ///    interfaces, such as a System.Data.DataSet or an System.Array. The default
        ///    is null.
        ///
        ///Exceptions:
        ///  System.ArgumentException:
        ///    The assigned value does not implement the System.Collections.IList or System.ComponentModel.IListSource
        ///    interfaces.
        /// </summary>
        [DefaultValue("")]
        [AttributeProvider(typeof(IListSource))]
        [RefreshProperties(RefreshProperties.All)]
        [Browsable(true)]
        public new object DataSource
        {
            get
            {
                return base.DataSource;
            }
            set
            {
                base.DataSource = value;

            }
        }

        /// <summary>
        /// Gets and sets an integer array of the values based on checked items values ID
        /// </summary>
        [Bindable(true), Browsable(true)]
        public List<int> ValueList
        {
            get
            {
                ///Gets checked items id values in a list
                List<int> retArray = new List<int>();
                PropertyDescriptor prop = null;
                PropertyDescriptorCollection propList = this.DataManager.GetItemProperties();
                prop = propList.Find(this.ValueMember, false);
                object checkedItem;
                if (prop != null)
                {
                    for (int i = 0; i < this.Items.Count; i++)
                    {
                        if (this.GetItemChecked(i))
                        {
                            checkedItem = this.DataManager.List[i];
                            retArray.Add(Convert.ToInt32(prop.GetValue(checkedItem).ToString()));
                        }
                    }
                }
                return retArray;
            }

            set
            {
                ///Sets checked items base on id values in a list
                List<int> myList = value;
                PropertyDescriptor prop = null;
                PropertyDescriptorCollection propList = this.DataManager.GetItemProperties();
                prop = propList.Find(this.ValueMember, false);
                object checkedItem;
                int intValItem;
                int found;
                if (prop != null)
                {
                    for (int i = 0; i < this.Items.Count; i++)
                    {
                        checkedItem = this.DataManager.List[i];
                        intValItem = Convert.ToInt32(prop.GetValue(checkedItem).ToString());
                        found = (from c in myList where c == intValItem select c).Count();
                        if (found == 1)
                            this.SetItemCheckState(i, CheckState.Checked);
                        else
                            this.SetItemCheckState(i, CheckState.Unchecked);
                    }
                }
            }
        }

测试:

        DataTable setData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Rows.Add(1, "涂聚文");
            dt.Rows.Add(2, "Geovin Du");
            dt.Rows.Add(3, "geovindu");
            dt.Rows.Add(4, "涂鸦王国");
            dt.Rows.Add(5, "涂氏");
            dt.Rows.Add(6, "张氏");
            dt.Rows.Add(7, "郭氏");
            dt.Rows.Add(8, "江氏");
            return dt;
        }

        /// <summary>
        ///
        /// </summary>
        public CheckedlistboxForm()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckedlistboxForm_Load(object sender, EventArgs e)
        {
            this.duCheckedListBox1.DataSource = setData();
            this.duCheckedListBox1.DisplayMember = "Name";
            this.duCheckedListBox1.ValueMember = "ID";
            //设定
            bool  insideCheckEveryOther = true;
            for (int i = 0; i < duCheckedListBox1.Items.Count; i++)
            {
                // For every other item in the list, set as checked.
                if ((i % 2) == 0)
                {
                    // But for each other item that is to be checked, set as being in an
                    // indeterminate checked state.
                    if ((i % 4) == 0)
                        duCheckedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
                    else
                        duCheckedListBox1.SetItemChecked(i, true);
                }
            }
            insideCheckEveryOther = false;

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            IEnumerator myEnumerator;
            myEnumerator = duCheckedListBox1.CheckedIndices.GetEnumerator();
            int y;
            //选择为全为无选
            //while (myEnumerator.MoveNext() != false)
            //{
            //    y = (int)myEnumerator.Current;
            //    duCheckedListBox1.SetItemChecked(y, false);
            //}

            //foreach (object itemChecked in duCheckedListBox1.CheckedItems)
            //{
            //    MessageBox.Show("Item with title: \"" + itemChecked.ToString() +
            //            "\", is checked. Checked state is: " +
            //            duCheckedListBox1.GetItemCheckState(duCheckedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
            //}

            foreach (DataRowView itemChecked in duCheckedListBox1.CheckedItems)
            {
                MessageBox.Show("Item with title: \"" + itemChecked[0].ToString() + itemChecked[1].ToString() +
                        "\", is checked. Checked state is: " +
                        duCheckedListBox1.GetItemCheckState(duCheckedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
            }
        }
    }



时间: 2024-09-13 04:22:09

csharp:A Custom CheckedListBox with Datasource的相关文章

Csharp:Windowsform using CheckedListBox Datasource

/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ListboxCheckboxForm_Load(object sender, EventArgs e) { //设置CheckedListBox中第i项的Checked状态 Da

Creating Custom Portal Modules

--------------------------------------------------------------------------------A portal module combines some code and UI to present specific functionality to the user (for example, a threaded discussion) or render data, graphics and text, (for examp

Csharp run sql script create database

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Data.Sql; using Microsof

winform 里CheckedlistBox如何将数据库设置好的值绑定到该控件并置为checked

问题描述 在Winform下,CheckedlistBox如何将数据库设置好的值绑定到该控件并置为checked?我的思路是:1.先将数据库所有数据绑定起来,2.再读取数据库中设置好的值,放入DataTable.3.根据2.中的DataTable的值遍历并与1.中的值对比,如果相等就置为checked.现在的问题是第三步如何写?我没有找到控件方法,向大家请教了. 解决方案 解决方案二:你是从数据库里面查询到的值然后绑定到checkedListBox上面吗,然后从另外一张表里面读取字段的值要和ch

vb.net checkedlistbox 绑定数据库后数据库如何删除标记记录?

问题描述 请教高手在vb.net中把checkedlistbox绑定数据库后数据库后,要删除数据库里的记录,如何实现?shujuku.Open()Dimlianxiren="Select*From联系人信息"DimlshujukuAsNewOleDb.OleDbDataAdapter(lianxiren,shujuku)Dim联系人dataset1AsNewDataSet联系人dataset1.Clear()lshujuku.Fill(联系人dataset1,"联系人信息&q

Alter dataSource in Spring By AOP And Annotation

Here is an article of how to use AOP and Annotation mechanism to alter dataSource elegantly. First, I want make sure that everyone knows how to build multiple dataSource. Please check this article Dynamic-DataSource-Routing After this, we will have a

Custom tool error: Failed to generate code for the service reference &amp;#215;&amp;#215;&amp;#215;&amp;#215;&amp;#215;&amp;#215;. Please check other erro

开发工具:VS2010 问题描述: 在ProjectName.Web中创建的WebService服务,然后在项目中添加Add Service Reference,然后就报"Custom tool error: Failed togenerate code for the service reference ××××××. Please check other error andwarning messages for details. "这样的错误  新建.调用WebService 解

webshpere studio application developer 中 jndi 访问DATASOURCE DB.7.2

application|web|访问 webshpere studio application developer 中 jndi 访问DATASOURCE出现下面的错误,请高手帮忙! 在服务器上我设置了DATasource是jdbc/ds1 Get connection failed.javax.naming.NamingException: The JNDI operation "lookup"on the context "localhost/nodes/localhos

2Photoshop CS2 custom menu自定义菜单功能

菜单 文/5D多媒体 出处:云绯流 Photoshop CS2 增加了很多新功能,其中就有很多为了方便用户使用而设立的功能.现在就讲其中一个custom menu自定义菜单功能的使用方法. 打开photoshop CS2,选择 编辑--菜单(Edit > Menus)或者按 Ctrl + Alt + Shift + M,打开对话框. 这里面ADOBE已经做了一些菜单的预设供你选择,这些预设的默认保存路径是Photoshop CS2 > Presets > Menu Customizati