0

I have a datagridview and a textbox. When the user enter some letter in the textbox, I want the datagridview to be sort and show results as the text of the textbox. But if the user dont type anything in the textbox or erase what is in the textbox, I want the datagridview to show all the results of my Database. Actually, I've success at it 2 weeks ago, but I've made some changes and now it doesn't work anymore.

Here is my code:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
        maConnexion.Open();
        string Var1 = textBox1.Text;
        SqlCommand command = maConnexion.CreateCommand();
        SqlCommand command1 = maConnexion.CreateCommand();

        if (Program.UserType == "admin")
        {
            if (textBox1.Text != String.Empty)
            {
                command.Parameters.AddWithValue("@SerialNum", Var1 + "%");
                command1.Parameters.AddWithValue("@SerialNum", Var1 + "%");
                command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE @SerialNum AND FComponent IS NOT NULL";
                command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE @SerialNum And FComponent IS NOT NULL";
            }
        }
        else
        {
            if (textBox1.Text != String.Empty)
            {
                command.Parameters.AddWithValue("@SerialNum", Var1 + "%");
                command1.Parameters.AddWithValue("@SerialNum", Var1 + "%");
                command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE  (SerialNum LIKE @SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL  ";
                command1.CommandText = "SELECT DISTINCT SerialNum, Machine, BoardName, BoardNumber FROM FailAndPass WHERE  ReportingOperator IS NULL AND FComponent IS NOT NULL AND (SerialNum LIKE @SerialNum) ";
            }
        }

        if (!string.IsNullOrWhiteSpace(textBox1.Text))
        {
            SqlDataAdapter sda = new SqlDataAdapter(command);
            SqlDataAdapter sda1 = new SqlDataAdapter(command1);
            DataTable dt = new DataTable();
            DataTable dt1 = new DataTable();
            sda.Fill(dt);
            sda1.Fill(dt1);

            DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
            DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
            dcIsDirty.DefaultValue = false;
            dcIsDirty1.DefaultValue = false;
            dt.Columns.Add(dcIsDirty);
            dt1.Columns.Add(dcIsDirty1);

            dataGridView1.DataSource = dt;
            dataGridView2.DataSource = dt1;
            maConnexion.Close();

            dataGridView1.Columns[6].Visible = false;
            dataGridView2.Columns[3].Visible = false;

        }
    }

As you will see, the datagridview is fill, the user can edit columns and so write new data in Database by clicking on the button. But then if the user write a serialNum in the textbox, it just show ONE results.. and not all the results beginning by B0033 for exemple.

Luke
  • 751
  • 2
  • 7
  • 32
Alexis Rin
  • 41
  • 8
  • Please post a [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). I think there is a lot of unnecessary code in your question . – Luke Jul 20 '17 at 13:50
  • Edit and change. – Alexis Rin Jul 20 '17 at 13:59
  • Please accept my edit - I removed the commented code as well. What exactly did you change, that made it stop working? – Luke Jul 20 '17 at 14:04
  • 1
    Rather than re-querying your data with each `TextChanged` event, consider [using a filter](https://stackoverflow.com/a/31818204/3773066) on your `DataTable` source. – OhBeWise Jul 20 '17 at 14:04
  • @OhBeWise I was just about to write that. +1 – Luke Jul 20 '17 at 14:05
  • @Luke I had a problem with my datagridview and a combobox that i wanted to put inside. The combobox was grey-ish / wasn't dropping down and showing values. But that's in another part of the code. – Alexis Rin Jul 21 '17 at 06:29
  • @OhBeWise I've used your filter. It's same as mine. And it doesnt change anything, i still have the problem : when the user delete what he wrote in the textbox, the datagridview doesnt refresh. And it still show only one row. – Alexis Rin Jul 21 '17 at 06:51
  • You must requerry your Data on the text changed event. This might works for a few clients. But as soon as you have more clients it will almost kill your SQL instance. If you dont use any filters and still only get one row there will most likely be something wrong with your querry. Get the querry you are running into your clipboard and run it manually on SQL Management studio to check, if you get results. – Luke Jul 21 '17 at 09:42
  • i dont understand the word requerry. My query are running fine into SQL MS. – Alexis Rin Jul 21 '17 at 09:56
  • On each TextChange Event (Event will fire 5 times if you just hype hello) you send new commands to your sql database (you re-querry). That will work fine for few clients, terrible for more. In addition it will slow down your application as soon as the sql database is not hosted on the same computer as your application is running – Luke Jul 21 '17 at 09:58
  • So how can i avoid re-querry since i'm new into c# and that's the only way i found to do sql command.? – Alexis Rin Jul 21 '17 at 10:11
  • `command1.Parameters.AddWithValue("@SerialNum", Var1 + "%");` Are you sure it works this way? I'd put the `'%'` into the CommandText. As said, it might works this way as well. – Luke Jul 21 '17 at 13:38
  • Yes sir, it was working that way ! – Alexis Rin Jul 24 '17 at 07:29

1 Answers1

0

As described in the comments you do not want to requery each time the text changed. I wrote some code to get you started. You will have to transform it into code for your application.

// Put this to the event or sub where you want to query for data
 Private DataGridView dgv;
 Private DataView _tblView;
 private void Form1_Load(object sender, EventArgs e) {
        DataTable tbl = myModule.GetDataTableWithRows();
        //  Imagine we have Columns "CutomerID", "CustomerLastName", "CustomerPriority"
        _tblView = new DataView(tbl);
        _tblView.RowFilter = "";
        dgv.DataSource = _tblView;
    }

And Then your TextChangedEvent

 private void txtChanged(object sender, EventArgs e) {
        _tblView.RowFilter = ("CustomerLastName like \'" + (mytextBox.Text + "\'"));
    }

This way your application will do the filtering.

There are also wildcards for the rowfilter, I think % for any char any amount of chars. For more information take a look at DataView MSDN

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Luke
  • 751
  • 2
  • 7
  • 32
  • It's been a while since i've seen people using form_load. What is this ? is this a sort of constructor ? – Alexis Rin Jul 21 '17 at 12:28
  • I have an exception that i haven't seen before : System.InvalidOperationException : 'ExecuteReader : The propriety CommandText has not been initialize. What does it mean? :/ – Alexis Rin Jul 21 '17 at 12:39
  • I've put your code into mine and done the change. I don't have any errors, perhaps it doesn't work. And by that, i mean that if i write "B0016" it doesn't filter nor do anything. – Alexis Rin Jul 21 '17 at 12:49
  • I just took a look into your SO profile. Seems you are asking a lot of questions. Are you generally new to programming? Keep in mind that learning programming is mainly about finding out how stuff works. You will learn stuff better, when you look for answers and find them yourself, instead of asking questions. Asking a new question on SO should always be the very last step imo. – Luke Jul 21 '17 at 13:35
  • Im absolutely not new in programming, I'm in third grade engineer school.. I'm kinda new on C# although i've done research and learned some courses on the internet since 2 month. The thing is i'm currently in internship and i work on a big application (It will be use by some other country). This is my last week at the factory and where i can work on the application so i need to finish it fast. ^^ – Alexis Rin Jul 24 '17 at 07:28