Click to See Complete Forum and Search --> : what's wrong with this code? binding Dataset to gridview


cool disel
01-27-2009, 08:39 AM
hi i'm a new web developer and i was wondering what's wrong with this code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from [UserTable]");

// creating the data adapter
SqlDataAdapter DA = new SqlDataAdapter();
DA.SelectCommand = cmd;

//creating datasets
DataSet DS = new DataSet();
DA.Fill(DS, "UserTable");

// creating data view
DataView DV = new DataView();

//creating data table
DataTable DT = new DataTable();

//PagedDataSource PDS = new PagedDataSource();



GridView1.DataSource = DA;

con.Close();


}
}


it gives an error

"Fill: SelectCommand.Connection property has not been initialized."

in this line
DA.Fill(DS, "UserTable");

thanx :)

redjay
01-31-2009, 05:38 AM
you select command:

SqlCommand("select * from [UserTable]");

seems to be missing the connection parameter as shown inn the following syntax I found

SqlCommand(query, conn)

click here (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(VS.71).aspx)to see the example

Does this help?

cool disel
01-31-2009, 05:49 AM
thanx but i managed to get another code running :)

if (!this.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Reviews]", conn))
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
try
{
conn.Open();

DataSet ds = new DataSet();
adapter.Fill(ds);

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


}
catch
{
throw new Exception("Unable to bind to GridView");
}
}
}