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

Asked

Viewed 1,685 times

0

Hello! I’m actually starting at C# and I already have small projects. I can already connect to the remote database, I can already run queries, I just can’t get the result of a Select and show in a Datagridview. Honestly, if there is a simpler method/element to work with than Datagridview, I will be happy.

Use this code to create 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 don’t 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?
            }
        }
    }
  • Is using winforms?

1 answer

2


You can use 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];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.