Bind the result of LINQ query to a control

by Euo 6. September 2008 02:33

As I am experimenting with the new feature of VS 2008 - the LINQ, I came across of needing to bind a datasource to an object. The datasource that I want to use is the result of my LINQ query statement. Here is what I got and done.

First, create a LINQ-to-SQL class. 

 

 

Now that I already have my LINQ-to-SQL mark-up language, I can now run a query against it like to any ordinary database. Construct the query statement: 

            var db = new WITWAY_DATADataContext();
            var branches = from branch in db.Branches.AsEnumerable<Branch>()
                           select branch;

 The WITWAY_DATADataContext class is the generated object that the LINQ-to-SQL provided. It is where the representation of our database resides. The generic AsEnumerable<Branch> extension method tells that the we want the query's result to be enumerable of Batch type. 

 Now, bind the result to, say, DropdownList.

if (!IsPostBack)
        {         
            var db = new WITWAY_DATADataContext();
            var branches = from branch in db.Branches.AsEnumerable<Branch>()
                           select branch;

            ddlBranch.DataSource = branches;
            ddlBranch.DataValueField = "uid";
            ddlBranch.DataTextField = "Name";
            ddlBranch.DataBind();
        }

 

Tags:

Development

About the author

Something about the author

Month List

Page List