2

I am using a SQL Server database, I have a table with multiple columns ([First Name], [Last Name]), I display it in the datagridview. I also have a single textbox (txtBoxSearch) in my UI. How can I search in two columns using only 1 string?

I call this method when navigated to the user screen to load the the data in the datagridview:

private void LoadData() {
        try {
            string sqlCommand = "SELECT * from tbl_user";
            con = new SqlConnection(connectionString);

            dataAdapter = new SqlDataAdapter(sqlCommand, connectionString);

            table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            dataGridProducts.DataSource = table;
        } catch (Exception ex) {
            MessageBox.Show(string.Format("An error occurred: {0}", ex.Message), "Error");
        }
    }

This is my code, it works for the first search, but after searching again it will show no record found.

if (!string.IsNullOrWhiteSpace(txtBoxSearch.Text)) {
                try {
                    using (SqlConnection con = new SqlConnection(connectionString)) {
                        con.Open();
                        string sqlCommand = "SELECT * FROM tbl_user WHERE CONCAT([First Name], [Last Name]) LIKE '%" + txtBoxSearch.Text + "%'";
                        using (SqlCommand cmd = new SqlCommand(sqlCommand, con)) {

                            DataTable dt = new DataTable();
                            SqlDataAdapter ad = new SqlDataAdapter(cmd);
                            ad.Fill(dt);

                            if (dt.Rows.Count > 0) {
                                dataGridProducts.DataSource = dt;
                            } else {
                                MessageBox.Show("No record found.", "Error");
                            }
                        }
                    }
                } catch (Exception ex) {
                    MessageBox.Show(string.Format("An error occurred: {0}", ex.Message), "Error");
                } finally {
                    con.Close();
                }
            }
  • What does "show nothing" mean? – PepitoSh Jun 25 '18 at 03:54
  • Looks fine to me (minus using `SELECT *` but I digress). Can you post more code? – Zer0 Jun 25 '18 at 03:54
  • The above SQL should search the same all the time, every time. So there is something wrong with your surrounding code – Fandango68 Jun 25 '18 at 03:55
  • Take a look at :https://stackoverflow.com/a/42759069/7124761 – Prashant Pimpale Jun 25 '18 at 03:58
  • Take a look at :https://stackoverflow.com/a/42759069/7124761 – Prashant Pimpale Jun 25 '18 at 03:58
  • [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Jun 25 '18 at 03:59
  • updated the question , @PepitoSh the result is empty , on my table , there is a data entry FNAME: test and test1. when I search for test1, the datagrid will display the test1 entry which is correct , bu after i search for "test" again , no results is displayed. –  Jun 25 '18 at 03:59
  • What is the row count in the table? It could be that you just don't display properly the otherwise good data returned from the query. – PepitoSh Jun 25 '18 at 04:01
  • @PepitoSh there is no data entry –  Jun 25 '18 at 04:02
  • Sounds to me like you're simply not executing the query on subsequent searches? If you could provide code that reproduces the behavior that would make it easier. – Zer0 Jun 25 '18 at 04:06
  • @Zer0 I already provided my full search method –  Jun 25 '18 at 04:07
  • That code does not even compile due to `BindingSource.` – Zer0 Jun 25 '18 at 04:08
  • @Zer0 yes it shouldnt be there , updated the code –  Jun 25 '18 at 04:36

5 Answers5

3

Several problems I see here. I mocked up your simple table, and ran the below code and it works just fine.

string sqlCommand = "SELECT [Fist Name], [Last Name] FROM tbl_user WHERE [First Name] LIKE '%" +
txtBoxSearch.Text + "%' OR [Last Name] LIKE '%" + txtBoxSearch.Text + "%'";
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
using(var dataAdapter = new SqlDataAdapter(sqlCommand, connectionString))
{
    dataAdapter.Fill(table);
}
dataGridUser.DataSource = table;

You don't need SqlCommandBuilder as far as I can see. You also don't need a BindingSource nor do you use it.

Only difference I'm doing here is disposing of dataAdapter.

The above code works just fine on a button click, for example.

I suspect you're not posting all code. If at all possible please post code that can fully reproduce the issue.

Zer0
  • 7,191
  • 1
  • 20
  • 34
  • Hi I updated the question , I also included how I populate the datagrid. Thanks –  Jun 25 '18 at 05:57
  • @NicoTing I see your update. Your code should work. And my code above does. How is your second block of code called? Perhaps it's not running the UI thread? But, by default, this should throw an `Exception`. So far I don't have enough to reproduce your issue. – Zer0 Jun 25 '18 at 21:00
  • the LoadData() method is called when navigated to the UserUI, and on my txtboxsearch keydown event , when the user hits enter key , the provided code is my exact code. –  Jun 26 '18 at 00:43
  • @NicoTing Your code should work. Maybe try a call to `Refresh` on your `DataGridView` after updating the `DataSource`? Also validate that the `DataTable` has rows in it. – Zer0 Jun 26 '18 at 00:46
  • Thank u @zer0 , I will try that now. –  Jun 26 '18 at 00:51
  • HAHAHAHA now I know whats happening lol , because when I hit enter , the "test" is still in there , and the state is "test \n test1" lolol –  Jun 26 '18 at 00:58
  • I already have the Sportsmanship badge, but appreciate your time and effort. – Jeremy Thompson Jun 29 '18 at 09:06
0
BindingSource.
table = new DataTable();

You've taken out the code that shows us why it wont work the second time.


Update:

Please go through all the solutions here: Getting blank rows after setting DataGridView.DataSource

  1. DataGridView.AutoGenerateColumns = false
  2. The DataPropertyNames have been set
  3. DataGridView.ColumnCount = 0; as new columns maybe hiding the data the second time.
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • True, but this doesn't answer why it isn't working. This should be a comment not an answer. – Zer0 Jun 25 '18 at 04:11
  • where should I put this line? do I need to change something on my code? –  Jun 25 '18 at 04:13
  • Can you add the code, I suspect the problem is to do with the BindingSource. – Jeremy Thompson Jun 25 '18 at 04:18
  • @Zer0 I'll fix it when I get the code. Right now, the answer is we cant tell due to missing code. – Jeremy Thompson Jun 25 '18 at 04:19
  • @JeremyThompson Fair enough. And according to the code he's not even using a `BindingSource` due to this line `dataGridUser.DataSource = table;` – Zer0 Jun 25 '18 at 04:20
  • @Zer0 yes, Iam not using BindingSource, I used DataSource –  Jun 25 '18 at 04:24
  • @NicoTing do you want to show us the FULL code? If you're not using BindingSource, why is it in the code? You assign a DataTable to the DataGridViews DataSource, but you could also assign a BindingSource to the DataGridViews DataSource and this is where I think the problem iis. – Jeremy Thompson Jun 25 '18 at 04:25
  • @NicoTing So answer our question then? Why do you have `BindingSource.` in your code which won't even compile? – Zer0 Jun 25 '18 at 04:25
  • I updated the provided code, I am sorry the .BindingSource should not be there. –  Jun 25 '18 at 04:27
  • I think what I need is to Populate a new data table and bind it to the BindingSource. –  Jun 25 '18 at 04:29
  • Put a breakpoint on the `dataGridUser.DataSource = table;` the second time you call the function check if the `table` is empty. If it is the problem is with SQL if its not empty then the problem is assigning the table to the DataSource. – Jeremy Thompson Jun 25 '18 at 04:45
  • Hi I updated the question , I also included how I populate the datagrid. Thanks –  Jun 25 '18 at 05:57
  • I tried the update code and can't reproduce the problem. Unless you clear the textbox I get the same results the second time. There's something you're not showing us. You forgot to tell me the results of the breakpoint, is the DataTable empty on the second run? Without that info you could be troubleshooting in the wrong place. . . – Jeremy Thompson Jun 25 '18 at 08:14
0

You assign commandBuilder but not use it. Please refer to the SqlCommandBuilder documentation:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder(v=vs.110).aspx

builder.GetUpdateCommand();
PepitoSh
  • 1,774
  • 14
  • 13
  • Hi I updated the question , I also included how I populate the datagrid. Thanks –  Jun 25 '18 at 05:57
0

Found out that there is nothing wrong with my code, my textbox MultiLine property is set to true. That is why when I hit enter key the previous text is still in the textbox.

BTW, Thank you to everyone who shared their ideas :)

Jason Geiger
  • 1,912
  • 18
  • 32
  • 1
    Facepalm. Please checkmark this answer, or whatever you found most useful, to show the question has been answered. Remember you're free to upvote as many answers as you'd like that you considered helpful. – Zer0 Jun 26 '18 at 06:29
  • @Zer0 the problem was 30cm in front of the keyboard. Nico I'll reverse the downvote for telling us. Hitting enter when the focus is on the textbox doesn't invoke the default form button. – Jeremy Thompson Jun 26 '18 at 07:56
  • Another question why would WHERE LIKE ’%%' care about a carriage return? – Jeremy Thompson Jun 26 '18 at 08:53
  • @JeremyThompson It doesn't. Problem was simply an empty `DataTable`. If command was a problem there's the `try catch`. If `DataTable` is empty there's a check with a `MessageBox` error. Simple case of not checking the command text. – Zer0 Jun 26 '18 at 23:18
-1
private void txtsearch_TextChanged(object sender, EventArgs e)
{
    (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("ProductCode LIKE '{0}%' or ProductName LIKE '{1}%' or Type LIKE '{2}%' ", txtsearch.Text, txtsearch.Text, txtsearch.Text);
}
vahdet
  • 6,357
  • 9
  • 51
  • 106