luni, 25 august 2014

LINQ to DataSet - Filtering with DataView C#

DataView can be created from a LINQ to DataSet query. 

Example: 

Create a DataView from a LINQ to DataSet query with a Where clause

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add("Product");

            DataTable dt = ds.Tables[0];
            dt.Columns.Add("id"typeof(Int32));
            dt.Columns.Add("name"typeof(string));
            dt.Columns.Add("quantity"typeof(Int32));

            fillDataTable(dt);

            EnumerableRowCollection<DataRow> query = from p inds.Tables[0].AsEnumerable()
                                                     where p.Field<Int32>("quantity") > 50 && p.Field<Int32>("quantity") < 70
                                                     select p;
            DataView view = query.AsDataView();
            BindingSource bs = new BindingSource(); 
            bs.DataSource = view;
        }

        void fillDataTable(DataTable dt)
        {
            for (int i = 0; i < 100; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = i;
                dr[1] = "Product ";
                dr[2] = i;
                dt.Rows.Add(dr);
            }
        }
    }
}

Niciun comentariu:

Trimiteți un comentariu