Pergunta

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);
}
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top