ASP.NET local SQL Server database C# gridview data binding Visual Studio 2013

Guillermo picture Guillermo · Nov 8, 2014 · Viewed 7.3k times · Source

I need some help because I've been trying different things but nothing seems to work properly the question itself is the one below.

How can I bind data to a grid-view in Visual Studio 2013 with a local SQL Server database using the code behind C# ?

Here is the C# I'm trying:

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
    con.Open();

    SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);

    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();

    GridView1.DataSource = ds;
    GridView1.DataBind();

    cmd.ExecuteNonQuery();

    con.Close();
}

Answer

Soner Gönül picture Soner Gönül · Nov 8, 2014

You just assing your empty DataSet to your Gridview's DataSource.

You need to use .Fill method fo fill your DataSet of SqlDataAdapter. You don't need to use ExecuteNonQuery. This method just executes your query. It doesn't return any data or something as a result.

Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter. You don't need to .Close() your database connections and objects when you use it.

using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
    cmd.CommandText = "SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]";
    using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
         DataSet ds = new DataSet();
         sda.Fill(ds);
         GridView1.DataSource = ds;
         GridView1.DataBind();
    }
}