GridView Data Binding at runtime

M

MoonWa

I have added a GRidView to my page but have not bound the data yet. How do I
bind my GridView to a SqlDataSource when a user clicks a button. Here is the
code I have but it does not work.

SqlDataSource editDS = new SqlDataSource();
editDS.ID = "editDS";
editDS.ConnectionString =
WebConfigurationManager.ConnectionStrings["collaborativesqlSecureConnectionString"].ConnectionString;
editDS.ProviderName = "System.Data.SqlClient";
editDS.SelectCommand = "SELECT [EventId], [EventDateTime] FROM
[MainEvents] WHERE " + dateStr + " LIKE EventDateTime";

// Bind GridView to data source
eventEditGV.DataSourceID = editDS.ID;

Page.DataBind();
 
P

Phillip Williams

You missed to add the SqlDataSource to your page's controls collection, by
executing the following line before you assigned its ID to the DAtaSourceID
of the GridView:
Page.Controls.Add(editDS.);

SqlDataSource is a server control that has to be added to the Page's
Controls collection before you can use it.

You could have alternatively carried out the entire DataSet retrieval
programmatically like this:
private System.Data.DataSet GetMainEventsDS(string dateStr )
{
string connectionString =
ConfigurationManager.ConnectionStrings["collaborativesqlSecureConnectionString"].ConnectionString;
System.Data.IDbConnection dbConnection = new
System.Data.SqlClient.SqlConnection(connectionString);
string queryString = "SELECT [EventId], [EventDateTime] FROM [MainEvents]
WHERE " + dateStr + " LIKE EventDateTime";
System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();

dbCommand.CommandText = queryString;
dbCommand.Connection = dbConnection;

System.Data.IDbDataAdapter dataAdapter = new
System.Data.SqlClient.SqlDataAdapter();

dataAdapter.SelectCommand = dbCommand;

System.Data.DataSet dataSet = new System.Data.DataSet();

dataAdapter.Fill(dataSet);
return dataSet;
}

And then assign the dataset to the GridView's DataSource property or through
an ObjectDataSource.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top