filter by colunna towards sql server

1

I need to be able to make a query in which I must filter by column, in which I have serial, date, among others, in order, that the query will show me results that are within that column.

The code in c # that I am using and that works for me is this:

String consulta = "select Date_Timer, Serial,Polo_1  from Electronico where Serial = '" + textBox1.Text +"'";
                SqlCommand cmd = new SqlCommand(consulta, cnn);
                SqlDataAdapter sqlDataAdap = new SqlDataAdapter(cmd);
                DataTable dtRecord = new DataTable();
                sqlDataAdap.Fill(dtRecord);
                dataGridView1.DataSource = dtRecord;

When I run with this code

  

I want to replace it with this code and it fails me to show the data:

String consulta = "select Date_Timer, '" + textBox1.Text + "','" + comboBox1.Text + "'from Electronico where Serial = '" + textBox1.Text + "'";
            SqlCommand cmd = new SqlCommand(consulta, cnn);
            SqlDataAdapter sqlDataAdap = new SqlDataAdapter(cmd);
            DataTable dtRecord = new DataTable();
            sqlDataAdap.Fill(dtRecord);
            dataGridView1.DataSource = dtRecord;

When I run with this code:

  

Could you help me, thanks.

    
asked by Geraldo Montas 31.07.2018 в 18:15
source

2 answers

1

Try it like this:

String consulta = "select Date_Timer, Serial," + comboBox1.Text + 
                  "from Electronico where Serial = '" + textBox1.Text + "'";
    
answered by 31.07.2018 в 18:22
1

Do not add single quotes ( ' ) in the query string:

String consulta = "select Date_Timer, Serial, " + comboBox1.Text + " from Electronico where Serial = '" + textBox1.Text + "'";

Apart from your specific question, I recommend that you do not build your queries like this, it is a code prone to injections SQL . I invite you to investigate more about the subject and continue practicing and improving your skills with this magnificent language;)

    
answered by 31.07.2018 в 18:46