Matt Winer
Matt Winer

Reputation: 535

Using Dataview with a MySQL populated DataGridView

I've taken over some code that I'm a bit unfamiliar with. We were using an access data source to populate a DGV.

I just changed it to fill the DGV from MySQL.

Here's a snip it of code from the Class I'm using to bind:

public void Bind(DataGridView dataGridView)


{
        string query = "SELECT * from vwFavoritesList";

        mySqlDataAdapter = new MySqlDataAdapter(query, mySqlConnection);
        mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);

        dataTable = new DataTable();
        mySqlDataAdapter.Fill(dataTable);

        bindingSource = new BindingSource();
        bindingSource.DataSource = dataTable;

        dataGridView.DataSource = bindingSource;
    }

I'm having an issue porting over the dataview commands we had before.

Here is the search code that we had before that worked awesome.

   private void txtSearch_TextChanged(object sender, EventArgs e)
    {

        DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
        dv.Sort = "Name ASC";
        dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
        dataGridView1.DataSource = dv;
    }

I've come up with:

  (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);

But when this runs I get this error: Object reference not set to an instance of an object.

Upvotes: 0

Views: 1366

Answers (2)

Xeidos
Xeidos

Reputation: 352

You did it right... You have to creat a new DataView and use your DataTable dt.

There is just one mistake, you have to call your dv.RowFilter and set the value in '' like:

private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "Name LIKE '" + txtSearch.Text.Trim() + "'";
            dataGridView1.DataSource = dv;    
        }

I hope this solved your problem! Have a nice day!

Upvotes: 0

Derek
Derek

Reputation: 8630

Your DataGridView is already bound to the DataTabe, so you should be able to just do this :-

dataGridView1.DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);

Upvotes: 1

Related Questions