I am currently creating and reading a DataTable with the following code in my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Sessio
The answers above are correct, but I thought I would expand another answer by offering a way to do the same if you require to pass parameters into the query.
The SqlDataAdapter
is quick and simple, but only works if you're filling a table with a static request ie: a simple SELECT
without parameters.
Here is my way to do the same, but using a parameter to control the data I require in my table. And I use it to populate a DropDownList
.
//populate the Programs dropdownlist according to the student's study year / preference
DropDownList ddlPrograms = (DropDownList)DetailsView1.FindControl("ddlPrograms");
if (ddlPrograms != null)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ATCNTV1ConnectionString"].ConnectionString))
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProgramID, ProgramName FROM tblPrograms WHERE ProgramCatID > 0 AND ProgramStatusID = (CASE WHEN @StudyYearID = 'VPR' THEN 10 ELSE 7 END) AND ProgramID NOT IN (23,112,113) ORDER BY ProgramName";
cmd.Parameters.Add("@StudyYearID", SqlDbType.Char).Value = "11";
DataTable wsPrograms = new DataTable();
wsPrograms.Load(cmd.ExecuteReader());
//populate the Programs ddl list
ddlPrograms.DataSource = wsPrograms;
ddlPrograms.DataTextField = "ProgramName";
ddlPrograms.DataValueField = "ProgramID";
ddlPrograms.DataBind();
ddlPrograms.Items.Insert(0, new ListItem("
Enjoy