C # - Display search results in DataGridView (SELECT SQL)

0

Hello! I'm starting effectively in C # and I already have small projects. I can already connect to the remote database, I can already execute queries, I just can not get the result of a Select and show in a DataGridView. Honestly, if there is a simpler method / element to work with than the DataGridView, I'll be happy.

Use this code to create the connection / command

static SqlConnection conect = new SqlConnection("Data Source=meuip;Initial Catalog=db;User ID=sa;Password=senha");
        SqlCommand cmd = new SqlCommand("SELECT * FROM Tabela where login='usuario'",conect);
        SqlDataReader dr;

and then on a specific button comes the problem. I do not know how to proceed.

        private void button3_Click(object sender, EventArgs e)
    {
        conect.Open();
        dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            if (dr.Read())
            {
               // Quero colocar os Resultados daqui num DataGridView. E agora?
            }
        }
    }
    
asked by anonymous 15.03.2016 / 22:33

1 answer

2

You can use the SqlDataAdapter and DataSet.

string sql_query = "SELECT * FROM Tabela where login='usuario'";

SqlDataAdapter data = new SqlDataAdapter(sql_query, conect);
DataSet tabela = new DataSet();
SqlCommandBuilder cmd = new SqlCommandBuilder(data);
data.Fill(tabela);
dataGridView1.DataSource = tabela.tables[0];
    
16.03.2016 / 00:14