Wednesday, May 1, 2013

How to Bind Dropdownlist in Asp.net using LINQ?



Introduction: In this post I have try to explain how to bind/fill Dropdownlist control from database in LINQ.

Description:

I have create a table name OFFICE_DEPARTMENT
ID_DP
int
DEPARTMENT_NAME
varchar(50)

ID_DP is primary key of table.
Now go to Visual studio>File>New website>Asp.net empty web site. Now go to Solution Explorer, right click on website>Add new item>Linq to Sql classes.

Now you see App_code folder will added to application and a dataclasses added with extension .dbml
in App_code folder.

Now check the web.config file of application. It self create a connectionstring for database.

Now connect the database to server explorer. After that drag and drop the table from database.

Add a web form to application. Go to Solution Explorer, right click on website>Add new item> Web from and drag and drop Dropdownlist from Toolbox.
<asp:DropDownList ID="ddlstate" runat="server">
        </asp:DropDownList>
Now got to .aspx.cs page and make an object of Dataclasses.
DataClassesDataContext db = new DataClassesDataContext();

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

    }
public void Filldropdown()
    {
        try
        {
            var statedrop = from c in db.OFFICE_DEPARTMENTs
                            select c;
            ddlstate.DataSource = statedrop;
            ddlstate.DataValueField = "ID_DP";
            ddlstate.DataTextField = "DEPARTMENT_NAME";
            ddlstate.DataBind();
            ddlstate.Items.Insert(0, new ListItem("--Select--", "0"));
        }
        catch (Exception EX)
        {
        }
    }
Now debug the application and check the result


Related Articles on LINQ:

Ø  What is LINQ? Its advantage, disadvantage and types

Ø  How to Bind Gridview Data Control in LINQ?

Ø  How to insert data into database using Linq?

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment