Fill datagridview with condition # Sql

0

Good friends. I am creating a project and I just ran into something that I can not solve. I have a datagridview where I show all the information of an employee:

        private void Mostrar(){ var query = from p in db.Usuarios_ 
                  select p;
        dataGridView1.Rows.Clear();
        foreach (var items in query)
        {

            dataGridView1.Rows.Add(
                                         items.Usuario.ToString(),
                                         items.Numidentidad.ToString(),
                                         items.NombreCom.ToString(),
                                         items.Genero.ToString(),
                                         items.Correo.ToString(),
                                         items.Telefono.ToString(),
                                         items.Cargo.ToString()
                );
        }
     }

Now, my headache came when I tried to fill in another datagridview only if in the Cargo Registry the condition that Cargo had to be equal to "Teacher" was fulfilled, that is, I only filled the datagridview with all the records of the teacher . I would greatly appreciate your help.

    
asked by Silvano Hernandez 08.12.2017 в 06:46
source

2 answers

0

add condition to query linq where p.Cargo == "Maestro" as shown

            var query = from p in db.Usuarios_
                        where p.Cargo == "Maestro"
                        select p;
            this.dataGridView1.Rows.Clear();
            foreach (var items in query)
            {

                dataGridView1.Rows.Add(
                                             items.Usuario.ToString(),
                                             items.Numidentidad.ToString(),
                                             items.NombreCom.ToString(),
                                             items.Genero.ToString(),
                                             items.Correo.ToString(),
                                             items.Telefono.ToString(),
                                             items.Cargo.ToString()
                    );
            }
    
answered by 08.12.2017 / 08:01
source
0

This you can do better with a lambda expression, that is:

var query = db.Usuarios_.Where(x=>x.cargo == "Maestro").ToList();

and I recommend, to remove that foreach, in the datagridview, create your columns and for each column, where DataPropertyName says, place the name of the field, in the case of the identity number, numIdentity, etc.

then you place dataGridView1.AutoGenerateColumns = false; and finally:

dataGridView1.DataSource = query;

that last as a suggestion to save code lines, I hope it serves you!

    
answered by 08.12.2017 в 15:20