Is it possible to make a DataTable as a AutoCompleteSource in a TextBox? (C#)
Jared is correct - you can't bind directly without doing some manipulation. Here's an example of using the LINQ DataSet extensions to retrieve a field as the autocomplete source:
DataTable dtPosts = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["StackOverflow"].ConnectionString))
{
conn.Open();
using (SqlDataAdapter adapt = new SqlDataAdapter("SELECT TOP 100 Id, Title, Body, CreationDate FROM Posts WHERE Title IS NOT NULL ORDER BY Id", conn))
{
adapt.SelectCommand.CommandTimeout = 120;
adapt.Fill(dtPosts);
}
}
//use LINQ method syntax to pull the Title field from a DT into a string array...
string[] postSource = dtPosts
.AsEnumerable()
.Select<System.Data.DataRow, String>(x => x.Field<String>("Title"))
.ToArray();
var source = new AutoCompleteStringCollection();
source.AddRange(postSource);
textBox1.AutoCompleteCustomSource = source;
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
Not directly, you'll want to read your datatable into an AutoCompleteStringCollection
.
You could do something like this (from here):
private AutoCompleteStringCollection GetAutoSourceCollectionFromTable(DataTable table)
{
AutoCompleteStringCollection autoSourceCollection = new AutoCompleteStringCollection();
foreach (DataRow row in table.Rows)
{
autoSourceCollection.Add(row[0]); //assuming required data is in first column
}
return autoSourceCollection;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With