How to bind LINQ query data to datagridview using Microsoft visual studio 2010?


LINQ stands for Language-Integrated Query.This article will demonstrates how to bind LINQ query resultset to datagridview. LINQ extends powerful query capabilities to the language syntax of C#. I hope it will be useful for all beginners of LINQ.

How to bind LINQ query data to datagridview using Microsoft visual studio 2010?
How to create entity model to retrieve data from database?
Add-> New Item -> ADO.NET Entity Data Model.
It will create Model1.edmx file.
Select Generate from database and click on Next.
It will ask you to create new connection.
Check checkbox "Save entity connection settings in App.config file".
Click on next and select tables , Views , stored procedure you want to add.
Click on Finish button to create entity model.
Creation of Windows form
Add-> New Item -> Windows form to create Form1.cs
Design windows form
Drag and drop datagridview and one button say btnRetrievedata.
Add following code in Form1.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FirstLINQ
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnRetrievedata_Click(object sender, EventArgs e)
{
yourEntityname obj = new yourEntityname();
//LINQ query
var dept = from o in obj.DEPARTMENTS
where o.DEPTNO == 1001
select o;
//This will bind data to datagridview
dataGridView1.DataSource = dept.ToList();
}

}
}

DEPARTMENTS is a name of the table present in the database used in entity model.
DEPTNO is column name in DEPARTMENTS.
Execute the application, you will get query result in datagridview at runtime.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: