这个方法是目前找到最简单的一种,如果想要更复杂的自动检索那就要自己去定制方法了
- 使用控件: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;
}