c# 设置文本框textBox自动检索

这个方法是目前找到最简单的一种,如果想要更复杂的自动检索那就要自己去定制方法了

  • 使用控件:winform的textBox 以及Dev的TreeList

先上效果:

  • 实现过程:

在窗体load时先将treelist的政区名称列绑定到textbox

            //文本框过滤(模糊查询)
            DataTable dtSource = treeListZQ.DataSource as DataTable;
            List<string> Data = new List<string>();
            foreach (DataRow dr in dtSource.Rows)
            {
                string name = dr["s_domainname"].ToString();
                Data.Add(name);
            }
            //重点代码
            this.textBox1.AutoCompleteCustomSource.Clear();
            this.textBox1.AutoCompleteCustomSource.AddRange(Data.ToArray());
            this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;

设置textBox的文本改变事件,值改变时自动检索以及修改treelist的节点定位:

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string ZQName = textBox1.Text;
            if (string.IsNullOrWhiteSpace(ZQName))
                return;

            TreeListNode pNode = this.treeListZQ.FindNodeByFieldValue("s_domainname", ZQName);
            if (pNode == null) return;

            treeListZQ.CollapseAll();//重置Tree
            string name = pNode["s_domainname"].ToString();
            int ZQLevel = pNode.Level;
            if (ZQLevel == 0)
            {

            }
            else if (ZQLevel == 1)
            {
                pNode.Expanded = true;
            }
            else if (ZQLevel == 2)
            {
                pNode.ParentNode.Expanded = true;
                pNode.ParentNode.ParentNode.Expanded = true;
            }
            else if (ZQLevel == 3)
            {
                pNode.ParentNode.Expanded = true;
                pNode.ParentNode.ParentNode.Expanded = true;
                pNode.ParentNode.ParentNode.ParentNode.Expanded = true;
            }
            this.treeListZQ.FocusedNode = pNode;
            pNode.Selected = true;
        }

细心的小伙伴可能看到了文本框在没有输入文字时,文本框内有灰掉的文字,这是用来提示文本空需要输入的内容:

方法分两步:

先判断输入框是否有文本,需要注册事件textBox1_Enter

        Boolean textboxHasText = false;
        private void textBox1_Enter(object sender, EventArgs e)
        {
            if (textboxHasText == false)
                textBox1.Text = "";

            textBox1.ForeColor = Color.Black;
        }

离开文本框时通过上面的判断,没有文字:显示提示文字,有文字取消提示

        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                textBox1.Text = "政区名称";
                textBox1.ForeColor = Color.LightSlateGray;
                textboxHasText = false;
            }
            else
                textboxHasText = true;
        }

以上参考链接:三小   惊风雨

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值