首页 > 解决方案 > Windows 应用程序中的自动完成功能

问题描述

如何在文本框中逐个字符地选择值,例如 HDPOS 自动完成文本框

我试过 在页面加载

private void loadproductName()
{
    DataTable dt = _poshelper.getproductName("Bill_Select_ProductName");
    if (dt.Rows.Count != 0)
    {
        string[] postSource = dt
                .AsEnumerable()
                .Select<System.Data.DataRow, String>(x => x.Field<String>("UniqueName"))
                .ToArray();

        var source = new AutoCompleteStringCollection();
        source.AddRange(postSource);
        txtItemName.AutoCompleteCustomSource = source;
    }     
}

休假中

private void txtItemName_Leave(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtItemName.Text))
    {
        DataSet ds1 = _poshelper.getproductNameExistWhileLeave(txtItemName.Text);
        if (ds1.Tables[0].Rows.Count == 0)
        {
            txtItemName.Text = "";
            txtItemName.Focus();
        }
        else
        {
            loadLeave(ds1);
            txtItemName.Focus();
        }
    }
}

我需要

如果我使用退格键删除一个字符,它将永久删除

一个

如果我删除,我需要第二张图片,这意味着我需要保留在文本框中

b

更新

更多澄清,来自评论

如果我按退格键,则不应删除文本框中的字符串。相反,它应该选择每个字符。每次我按退格键

标签: c#windowswinforms

解决方案


在这里,我建议进行更改以使您的文本框具有以下行为。

当您不希望在文本框中键入退格键时“附加建议”文本(如第一张图片所示)消失时,

你可以做到这些步骤

  • 获取当前文本框文本(删除最后一个字符,因为我们最后退格了)
  • 清除文本的文本
  • 将文本发送回文本框

在您的代码中进行以下更改

private void loadproductName()
{
  DataTable dt = _poshelper.getproductName("Bill_Select_ProductName");
  if (dt.Rows.Count != 0)
  {
    string[] postSource = dt
            .AsEnumerable()
            .Select<System.Data.DataRow, String>(x => x.Field<String>("UniqueName"))
            .ToArray();

    var source = new AutoCompleteStringCollection();
    source.AddRange(postSource);
    txtItemName.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
    txtItemName.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
    txtItemName.AutoCompleteCustomSource = source;
  }
}

我不确定你在LeaveEvent 中做什么。但是您可以添加textBox'KeyUp事件,并在该事件中添加如下代码。

private void txtItemName_KeyUp(object sender, KeyEventArgs e)
{
    // track for backspace
    if (e.KeyCode == Keys.Back)
    {
        if (txtItemName.Text != "")
        {
            string text = txtItemName.Text.Substring(0, txtItemName.Text.Count() - 1);
            txtItemName.Text = "";
            txtItemName.Focus();
            SendKeys.Send(text);
        }
    }
}

推荐阅读