C#_ComboBox控件实现自记忆输入的内容

这个功能可以利用在登陆界面的用户名输入上,首先得设置ComboBox的两个属性:

cboUserName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cboUserName.AutoCompleteSource = AutoCompleteSource.CustomSource;

然后实现两个主要方法,利用的是I/O的读写:

读取:

        private void LoadHistory()
        {
            string fileName = Path.Combine(Application.StartupPath, "log.db");
            if (File.Exists(fileName))
            {
                StreamReader r = new StreamReader(fileName, Encoding.Default);
                string name = r.ReadLine();
                while (name != null)
                {
                    this.cboUserName.AutoCompleteCustomSource.Add(name);
                    this.cboUserName.Items.Add(name);
                    name = r.ReadLine();
                }
                this.cboUserName.SelectedIndex = 0;
                r.Close();
            }
        }

保存:

        private void SaveHistory()
        {
            string fileName = Path.Combine(Application.StartupPath, "log.db");
            StreamWriter wr = new StreamWriter(fileName, false, Encoding.Default);
            foreach (string name in cboUserName.AutoCompleteCustomSource)
            {
                wr.WriteLine(name);
            }
            wr.Flush();
            wr.Close();
        }

 

然后就是在相应事件中调用,如果是保存的话,代码可以如下:

                    if (!cboUserName.AutoCompleteCustomSource.Contains(cboUserName.Text))
                    {
                        cboUserName.AutoCompleteCustomSource.Add(cboUserName.Text);
                        SaveHistory();
                    }

这里加一个if判断,是保证保存的内容不会重复。

读取的话,只需在界面登陆的事件或窗体构造函数中调用LoadHistory()即可,注意其中数据绑定对象是你自己的ComboBox控件

posted @ 2010-06-06 16:22  小 .xin  阅读(1232)  评论(0编辑  收藏  举报
回到页首