Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Thursday, 27 June 2013

Store Datatable Column Name in an Array Using LINQ

If you want to store datatable column values in an array using LINQ you can achieve this by the following ways.

string[] ColName = dt.Columns.Cast<DataColumn>().
                                   Select(x => x.ColumnName).ToArray();

Wednesday, 26 June 2013

Store Datatable Row Values in Jagged Array using LINQ

If you want to store values of a datatable in a jagged array using LINQ you can achieve in the following ways.

string[][] Value = dt.Rows.OfType<DataRow>().
                                Select(r => dt.Columns.OfType<DataColumn>().
                                Select( c => r[c.ColumnName].ToString()).ToArray()).
                           ToArray();

Saturday, 26 January 2013

LINQ to SQL Classes

LINQ to SQL classes that are mapped to database tables and views are called entity classes. The entity class maps to a record, whereas the individual properties of an entity class map to the individual columns that make up a record. Create entity classes that are based on database tables or views by dragging tables or views from Server Explorer/Database Explorer onto the Object Relational Designer (O/R Designer).



Demo :

1 - Open Visual Studio 2008 and create a new ASP.NET Web Application.
     File --> New --> Web Site --> Visual C# --> ASP.NET Web Application --> Give name of the  application (for Ex- LinqtoSqlClasses).

2 - Right-click on the "App_Data" folder and select Add --> New Item.

3 - Once the Add New Item windows opens select "LINQ to Sql Classes" and name it "Northwind.dbml" as follows:

4 - Now connect your Database in server explorer and drag and drop the tables to Northwind.dbml file. It will automatically converted into a class. See the image below.

   a) Click on server explorer.


    b) Click on connect to database.


      c) Enter credentials to connect to the database.

                
                     Click on OK button.

        d) Drag your table from server explorer and drop it to the dbml file.



               Press Ctrl+S to save your work.

    5 - Open your default.aspx page. Drag and drop grid view control from tool box menu on to the page.
   
    6 - Write the below code on the page load to fetch data from database.

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

          private void Bind()
         {
               NorthwindDataContext db = new NorthwindDataContext();

               var category = from c in db.Categories
                                      select c;

               grdCategory.DataSource = category;
               grdCategory.DataBind();
         }
            
    7 - Save and run the application. You will get your required output.