The first task
we'll do is to load the drop down list in the page load event with the list of
records in the UserAccounts table. We'll also add an extra entry in the list
to allow the user to select the option of creating a new user.
1.
Double click on the web form in Design view to create the Page_Load
event in the code behind.
2.
Add the following code to the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadUserDropDownList();
}
}
3.
The LoadUserDropDownList is a custom method that you must create.
private void LoadUserDropDownList()
{
using (OrderDBContainer db = new OrderDBContainer())
{
ddlUsers.DataSource = from u in db.UserAccounts_SelectAll()
orderby u.LastName
select new { Name = u.LastName + ", " + u.FirstName,
Id = u.Id };
ddlUsers.DataTextField = "Name";
ddlUsers.DataValueField = "Id";
ddlUsers.DataBind();
ddlUsers.Items.Insert(0, new ListItem("Create New User", ""));
}
}
Notice the from clause in this LINQ query. It is using the
db.UserAccounts_SelectAll method on the OrderDBContainer. This will execute
the stored procedure.
The drop down list's DataSource source property is set to
the results of the LINQ query. The DataTextField is then set to
"Name" which is the property in the dynamically created object. The
DataValueField is then set to "Id". The next line binds the data to
the drop down list. The last line adds a new item to the list in the first
position. The text of the item is "Create New User" and this will be
used to determine if the user is adding or updating an existing user.
Set this page as the startup page and run the project.
There are no records in the table yet so all you'll see is the "Create New
User" entry in the drop down list.