Live search in a DataTable

I have a WPF Browserapplication which gets data stored on a SQL Server, stores it in a DataTable and displays it in a DataGrid. Now I want to have a TextBox where you can search entries in the DataTable but when I load the Application I'm getting an error telling me, that the row [Company] cannot be found.

I think the problem is, that the DataTable isn't yet filled when the filter is being applied to the DataTable. Can someone please give me a hint how to make this working?

DataTable dt = new DataTable();

public Page1()
{
    InitializeComponent();
    showSQLData();
}

private void showSQLData() 
{
    string sqlConnectionString = @"blabla";
    string sqlCommandString = "SELECT * FROM Excel_import";

    using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
    {
        SqlCommand cmd = new SqlCommand(sqlCommandString, sqlConnection);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);

        adapter.Fill(dt);

        dataGridSQLData.ItemsSource = dt.DefaultView;
    }
}

private void textBoxSearch_TextChanged(object sender, TextChangedEventArgs e)
{
    dt.DefaultView.RowFilter = string.Format("Company LIKE '%{0}%'", textBoxSearch.Text);
}

Based on you latest comment I would guess that textBoxSearch_TextChanged is being fired from within the InitializeComponent() call. You could check that dt.Rows.Count > 0 in textBoxSearch_TextChanged and return if that condition is not met.

链接地址: http://www.djcxy.com/p/75238.html

上一篇: WPF Datagrid绑定到Combobox和Textbox

下一篇: 在DataTable中进行实时搜索