Rjey Rjey - 2 months ago 15
C# Question

Can't Establish A Connection To SQL Server Using ADO.NET

I'm trying to establish a connection to a local SQL server using this code:

dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
dataGridView1.DataSource = sda;


But when I press the button in my form it doesn't show me the data! What am i doing wrong?

Answer

you need something like this

dataGridView1.Visible = true;
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
        con.Open()
        SqlCommand com = new SqlCommand("select * from Form", con);
        SqlDataAdapter sda = new SqlDataAdapter(com);
        DataTable dt=new DataTable();
        sda.Fill(dt);   

        dataGridView1.DataSource = dt;//set it to datatable
        dataGridView1.DataBind();