0

I took an video from you tube to Retrieving Data from SQL Server using C# and ADO.Net

http://www.youtube.com/watch?v=4kBXLv4h2ig&feature=related

I Do the same as him in the video... I want to show data from an sql database in a DataGridView.

I get an error whit

da.Fill(dg);
dg.DataSource = dg.Tables[0];

I name my DataGridView dg...

Complete code

using System.Data.SqlClient;

namespace SQLconnection
 {
 public partial class Form1 : Form
{
    SqlConnection cs = new SqlConnection("Data Source=FRANK-PC\\SQLEXPRESS; Initial Catalog=Forc#; Integrated Security=TRUE");
    SqlDataAdapter da = new SqlDataAdapter();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        da.InsertCommand= new SqlCommand ("INSERT INTO tblContacts VALUES (@FirstName,@LastName)",    cs );
        da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
        da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastname.Text;

        cs.Open();
        da.InsertCommand.ExecuteNonQuery();
        cs.Close();
    }

    // Display data in dg
    private void button2_Click(object sender, EventArgs e)
    {
        da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);
        da.Fill(dg);


        dg.DataSource = dg.Tables[0];
    }


}

}

1
  • What is the error you are getting? Commented Sep 23, 2011 at 6:20

4 Answers 4

3

you should open the connection before filling the table with the data adapter, add this:

cs.Open();

DataSet ds = new DataSet();
da.Fill(ds);
cs.Close();

dg.DataSource = ds.Tables[0];

note that this is anyway a bad practice, there are trillions of examples here in SO on how to handle the SQLConnections, you should use a using block so that it gets closed and disposed immediately after usage and do not have connections or adapters or data tables or sqlcommand global to all form but create them only when/where needed.

You should actually move out all data access logic from the UI to a separated class, Business Logic or Data layer.

Edit:

you should do something like this:

using(SQLConnection conn = 'connection string here')
{
    using(SQLCommand cmd = new ('sql query', conn))
    {
        //execute it blah blah
    }
}

check out this question: Closing SqlConnection and SqlCommand c#

Sign up to request clarification or add additional context in comments.

4 Comments

impossible to convert from 'System.Windows.Forms.DataGridView' in 'System.Data.DataTable'
'System.Windows.Forms.DataGridView' no contain définition for'Tables' no method extension 'Tables' to accept a first argument type 'System.Windows.Forms.DataGridView' nothing found (a directive using or référence d'assembly miss ?) C:\Users\Frank\Documents\Visual Studio 2008\Projects\SQLconnection\SQLconnection\Form1.cs 42 32 SQLconnection
Is its posible to get complete code in a situation for your point '' you should use a using block so that it gets closed and disposed immediately after usage and do not have connections or adapters or data tables or sqlcommand global to all form but create them only when/where needed.''
Just combine my first snippet inside the second and you are good to go.
2

The Fill method open/close connection implicitly but the problem is in name of dataGrdiView and DataTable/DataSet reference variable - dg

private void button2_Click(object sender, EventArgs e)
    {
        da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);
        DataTable dt=new DataTable();
        da.Fill(dt);

        dg.DataSource = dt;
    }

2 Comments

Thanks work well! Why in the video work well without an instance of dataTable?
Yes in video DataSet is used. DataSet itself a collection of DataTables and Relations. Take a look at @Davide Piras's post.
0

I'm guessing since you didn't include the exception you are receiving, but you need to open your SqlConnection prior to using it:

private void button2_Click(object sender, EventArgs e)
{
   da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);

   cs.Open();
   da.Fill(dg);
   cs.Close();

   dg.DataSource = dg.Tables[0];
}

Comments

0

Try it this, but is important know what kind of exception throws.

private void button2_Click(object sender, EventArgs e)
{
        cs.Open();
        using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM tblContacts", cs))
        {
            DataTable t = new DataTable();
            a.Fill(t);

            dg.DataSource = t;
        }
    }

2 Comments

This is NOT correct. The using will dispose cs but cs will be still available as it was created before but will be not usable.
It's true, I fixed assuming the instance of cs created before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.