Home > ASP.Net, Linq > Three Ways to Bind DropdownList Using Linq

Three Ways to Bind DropdownList Using Linq


Hi all,

Try this example to show you Three Ways to Bind DropdownList Using Linq

Step1 :- Open VS2008 and create a new website

Step2 :- add new Linq to SQL DataContext  and name it “Northwind.dbml” and add Categories table in it

Step3 :- Add new Web page and fromDropdownList control inside page

<div>
    Select Category :-
        <asp:DropDownList ID="ddl_Category" runat="server" AppendDataBoundItems="True">
            <asp:ListItem Value="-1">-- Please Select --</asp:ListItem>
        </asp:DropDownList>
    </div>

Step4 :- In Code behind and the following code which will be used to Bind DropdownList

— First Way :-


private void BindCategories()
    {
        try
        {
            NorthwindDataContext dbml = new NorthwindDataContext();
            var str = "select * from Categories ";
            var category = dbml.ExecuteQuery<Category>(str);
            ddl_Category.DataTextField = "CategoryName";
            ddl_Category.DataValueField = "CategoryID";
            ddl_Category.DataSource = category.ToList();
            ddl_Category.DataBind();
        }
        catch
        {

        }
    }

— Second Way :-


private void BindCategories()
    {
        try
        {
            NorthwindDataContext dbml = new NorthwindDataContext();
            var category = from cat in dbml.Categories
                           select cat;
            ddl_Category.DataTextField = "CategoryName";
            ddl_Category.DataValueField = "CategoryID";
            ddl_Category.DataSource = category.ToList();
            ddl_Category.DataBind();
        }
        catch
        {

        }
    }

— Third Way :-


private void BindCategories()
    {
        try
        {
            NorthwindDataContext dbml = new NorthwindDataContext();
            var category = dbml.Categories;
            ddl_Category.DataTextField = "CategoryName";
            ddl_Category.DataValueField = "CategoryID";
            ddl_Category.DataSource = category.ToList();
            ddl_Category.DataBind();
        }
        catch
        {

        }
    }

and In Page Load add this code

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindCategories();
        }
    }

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net, Linq
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: