Eric R.
Eric R.

Reputation: 1125

Dynamically set wpf toolkit Autocompletebox Itemsource

I have an autocompletebox from the Wpf Toolkit within my wpf datagrid. Below is my xaml:

                    <DataGridTemplateColumn Header="Account Type">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <toolkit:AutoCompleteBox Text="{Binding Path='Account Type'}"   Populating="PopulateAccountTypesACB" IsTextCompletionEnabled="True" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

In my Populating event, I want to set the itemsource based off a query that I am running. Below is what I have so far for this:

    private void PopulateAccountTypesACB(object sender, PopulatingEventArgs e)
    {
        try
        {
            List<string> types = new List<string>();

            string accountQuery = "SELECT AccountType FROM AccountType WHERE AccountType LIKE '" + e.Parameter +"%'";

            SqlDataReader accountTypes = null;
            SqlCommand query = new SqlCommand(accountQuery, dbConnection);

            accountTypes = query.ExecuteReader();

            while (accountTypes.Read())
            {
                types.Add(accountTypes["AccountType"].ToString());
            }


            accountTypes.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

            // Close the DB if there was an error.
            if (dbConnection.State == ConnectionState.Open)
                dbConnection.Close();
        }
    }

How can I set the ItemSource in this funciton? I tried assigning a name to the autocompletebox and using that from the function, but I couldn't access it from there.

Upvotes: 0

Views: 1884

Answers (1)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

I'm not shure that this is a good idea - to execute search query within event handler, but to set ItemSource there just cast sender to AutoCompleteBox:

AutoCompleteBox accountType = (AutoCompleteBox)sender;
accountType.ItemSource = types;

Upvotes: 1

Related Questions