gridview文本框中的自动完成功能

时间:2013-06-17 13:12:35

标签: c# winforms datagridview

我有两个gridview textbox列。我在gridview的{​​{1}}列中分别使用了自动填充,但textbox gridview列都是 自动完成正在混合这些列中的数据。

如何在不混合textboxarticle_code数据的情况下显示自动完成功能?

这是我的代码:

yarn_count

第二个Gridview列

    AutoCompleteStringCollection namesCollection4=new AutoCompleteStringCollection(); 
string query = "select article_code from article_production";
con.Open();
SqlCommand cmb = new SqlCommand(query, con);
SqlDataReader dr = cmb.ExecuteReader();
if (dr.HasRows == true)
{
    while (dr.Read())
    {
        namesCollection4.Add(dr["article_code"].ToString());

    }
}
else
{
    MessageBox.Show("Data not found");
}

con.Close();
dr.Close();
int column = dataGridView1.CurrentCell.ColumnIndex;

if(column==8)
{
    TextBox tb = e.Control as TextBox;

    if (tb != null)
    {
        tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        tb.AutoCompleteCustomSource = namesCollection4;
        tb.AutoCompleteSource = AutoCompleteSource.CustomSource;

    }

}

2 个答案:

答案 0 :(得分:1)

 AutoCompleteStringCollection namesCollection1=new AutoCompleteStringCollection(); 
string query1 = "select yarn_count from yarn";
con.Open();
SqlCommand cmb1 = new SqlCommand(query1, con);
SqlDataReader dr1 = cmb1.ExecuteReader();
if (dr1.HasRows == true)
{
    while (dr1.Read())
    {
        namesCollection1.Add(dr1["yarn_count"].ToString());

    }
}
else
{
    MessageBox.Show("Data not found");
}

con.Close();
dr1.Close();
int column1 = dataGridView1.CurrentCell.ColumnIndex;

if (column1 == 9)
{

    TextBox tb1 = e.Control as TextBox;

    if (tb1 != null)
    {
        tb1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        tb1.AutoCompleteCustomSource = namesCollection1;
        tb1.AutoCompleteSource = AutoCompleteSource.CustomSource;
    }

}
else
{
namesCollection1.Clear();
}
finally{con.Close();}
  
    

我找到解决方案,我忘了写其他条件

  

答案 1 :(得分:0)

我已经测试过,这应该可以按你的意愿运行:

//EditingControlShowing event handler for your DataGridView
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
        DataGridViewTextBoxEditingControl cellEdit = e.Control as DataGridViewTextBoxEditingControl;
        cellEdit.AutoCompleteCustomSource = new AutoCompleteStringCollection();
        cellEdit.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        cellEdit.AutoCompleteSource = AutoCompleteSource.CustomSource;
        int colIndex = dataGridView.CurrentCell.ColumnIndex;
        if (colIndex == 8) cellEdit.AutoCompleteCustomSource.AddRange(new string[] { "Aaaa", "Bbbb", "Cccc" });
        else if (colIndex == 9) cellEdit.AutoCompleteCustomSource.AddRange(new string[] { "1234", "5678" });            
}

我不确定namesCollection的类型,如果要分配到AutoCompleteSource属性,则必须确定其类型为AutoCompleteStringCollection