Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a DataTable as a AutoCompleteSource in a TextBox? (C#)

Tags:

c#

Is it possible to make a DataTable as a AutoCompleteSource in a TextBox? (C#)

like image 691
yonan2236 Avatar asked Dec 28 '22 09:12

yonan2236


2 Answers

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;
like image 191
David Hoerster Avatar answered Jan 31 '23 06:01

David Hoerster


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;
}
like image 33
Jared Harley Avatar answered Jan 31 '23 07:01

Jared Harley