Populating an ASP.Net drop down list using LINQ to SQL with C#

This example shows how to populate an ASP.Net drop down list control using LINQ to SQL with C#.  This example uses a stored procedure called from within the code behind  of the ASP.Net page. A sample method passes in a user ID which is then passed to the stored procedure.

Once you have created the datacontext diagram for your application, simply create an instance of it and populate the control as so:

protected void sampleMethod(int userId)
{
     using (var dc = new MyApplicationDataContext())
     {
          ddlMyDropDownList.DataSource = dc.SP_myStoredProc(userId);
          ddlMyDropDownList.DataTextField = "USER_NAME";
          ddlMyDropDownList.DataValueField = "USER_ID";
          ddlMyDropDownList.DataBind();
     }
}

You can also add an inline value to be shown in the drop down list and insert it at any point in the list at runtime, like so:

protected void sampleMethod(int userId)
{
     using (var dc = new MyApplicationDataContext())
     {
          ddlMyDropDownList.DataSource = dc.SP_myStoredProc(userId);
          ddlMyDropDownList.DataTextField = "USER_NAME";
          ddlMyDropDownList.DataValueField = "USER_ID";
          ddlMyDropDownList.DataBind();
          ListItem li = new ListItem("Inline Value", "78");
          ddlMyDropDownList.Items.Insert(0, li);
     }
}

The above code creates a list item and assigns some text and a value to it. The last line then inserts the new item into the drop down list at the first index in the list (i.e. the top).