Saturday, March 24, 2012

Populate dropdown list

How can I populate a dropdownlist with data from a database using
Microsoft.ApplicationBlocks.Data ?
ThanksUse one of the SqlHelper methods. For instance, SqlHelper.ExecuteDataSet(.
. .), and then just map the DataSource = returnedDataSet.Tables[0];, and
then you can set which field for the text and the value. All the
applications blocks do is encapsulate the ado.net call, so instead of
creating your connection object, then command object and executing the
command to return something, you call a static method of SqlHelper passing
in a connection string or connection or transaction object, the query or
stored procedure to run, some other potential options, and you'll get a
result back.
I have wrapped the Data Access application block in my own class that, upon
instantiation, creates a connection from the connection string stored in my
config file, and then it's ready to exectue anything. On Dispose() of my
object, I close my connection.
Best regards,
Jeffrey Palermo
"Mark Goldin" <markgoldin@.comcast.net> wrote in message
news:ug6v1VccEHA.1764@.TK2MSFTNGP10.phx.gbl...
> How can I populate a dropdownlist with data from a database using
> Microsoft.ApplicationBlocks.Data ?
> Thanks
>
>
Mark,
If you look at the example in the Help for DropDownList there is one example
how to create a DropDownList through databinding.
Let us borrow some code from the example:
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
..
But what you are interested in is how get the data from MS Data Access Block
right? Then declare the "CreateDataSource();" to return a ICollection just
like in the example and in then use SqlHelper class one of the 2 ways:
1: This one uses the dataset - not best in perfomance but easy to start with
DataSet ds = SqlHelper.ExecuteDataset(myConnection, "MyStoredProc", myParams
);
DataView dv = new DataView(ds.Tables["myTable"]);
return dv;
2: Use DataReader - a bit more code but better performance
// Call ExecuteReader static method of SqlHelper class that returns a SqlDat
aReader
SqlDataReader dr = SqlHelper.ExecuteReader connection, "MyStoredProc", myPa
rams);
if ((dr != null) && (dr.HasRows))
{
//Create Your Table here like in the example
..
while (dr.Read())
{
//Create a New DataRow here and assign values for each row in the DataReader
...
}
DataView dv = new DataView(myTable);
return dv;
}
Something like this!
Good Luck!
Thomas Andersson

0 comments:

Post a Comment