AutoComplete in DataGridView using Win Forms
In this article we are going to look at how we can provide autocomplete functionality in the DataGridView while editing data in the DataGridView control. We get the data from the database using SqlDataAdapter. When you double click UserName field in the DataGridView and try to edit. The AutoComplete string is displayed.
In this article we are going to look at how we can provide autocomplete functionality in the DataGridView while editing data in the DataGridView control.
Step 1: Create a Windows Project and name it as "DataGridViewAutoCompleteDemo".
Step 2: Double click on Windows Form to generate Form Load event of Form as below:
private void Form1_Load(object sender, EventArgs e)
{
}
step 3:Add the following statement at the top of the file
using System.Data.SqlClient;
step 4:In the below code, in the Form load event, We are getting the data from the database and displaying it in the DataGridView. We are also preparing the data "UserName" to be displayed as autocomplete string while editing data in the DataGridView.
AutoCompleteStringCollection scAutoComplete = new AutoCompleteStringCollection();
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=OnlineTestDB;Integrated Security=True;Pooling=False");
SqlDataAdapter daUsers = new SqlDataAdapter("select PKUserId,UserName from UserProfile",con);
DataSet ds = new DataSet();
daUsers.Fill(ds, "UserProfile");
//Display PKUserId,UserName in the DataGridView
dataGridView1.DataSource = ds.Tables["UserProfile"];
SqlCommand cmd = new SqlCommand("Select distinct UserName from UserProfile",con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
scAutoComplete.Add(dr.GetString(0));
}
con.Close();
}
step 5:Click/Select on DataGridView and Press F4 to go to properties of DataGridView. Now go to Events Tab and Double click
EditingControlShowing event to generate the "dataGridView1_EditingControlShowing" event handler. In this event handler we are going to write the code to display in the AutoComplete textbox of the DataGridView while editing the UserName field.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ( dataGridView1.CurrentCell.ColumnIndex == 1 && e.Control is TextBox)
{
TextBox txtUserName = (TextBox)e.Control;
txtUserName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtUserName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtUserName.AutoCompleteCustomSource = scAutoComplete;
}
}
step 6: Press ctrl+F5 and run the application. double click any row of the data grid view and edit the name field. You can see the autocomplete textbox as shown below:
Thank U mem Thanks For Code
but i need ur some more help i want to know what is "scAutoComplete" sorry mem i m unable to understand about it . Plz Help Me