简体   繁体   English

使用 linq c# 在 datagridview 中显示特定记录

[英]Display a specific record in the datagridview using linq c#

I created a linq with this code:我使用以下代码创建了 linq:

DataClasses1DataContext DB = new DataClasses1DataContext();

I just want to see a specific record from a view whose first column code is 00080 in the datagirdview1 so that other records are not displayed.我只想从datagirdview1中第一列代码为00080的视图中查看特定记录,以便不显示其他记录。 What code should I write in the form1_load so I can see it?我应该在form1_load中写什么代码才能看到它? i get no record in datagridview with this code:我在 datagridview 中没有使用以下代码记录:

    dataGridView1.DataSource=
        DB.W0_Calc_BedBes_UseInViews.FirstOrDefault(x => x.C_Code =="00080");

A simple linq query would be something like this:一个简单的 linq 查询将是这样的:

DB.(Tablename).Where(x => x.(Id column name) == 00080) DB.(表名).Where(x => x.(Id 列名) == 00080)

In modern programming, you separate your model from how your model is displayed (your view).在现代编程中,您将 model 与 model 的显示方式(您的视图)分开。 This enables you to change your view without having to change your model, for instance, if you want to show your data as a Graph instead of a table, or if you want to display the data in a Listbox, your model don't have to change.这使您无需更改 model 即可更改视图,例如,如果您想将数据显示为图形而不是表格,或者如果您想在列表框中显示数据,您的 model 没有改变。

Similarly, small changes in your model doesn't have to mean that you need to change your view.同样,model 的微小变化并不一定意味着您需要更改视图。 It will also be possible to unit test your model without needing a windows form也可以在不需要 windows 表格的情况下对您的 model 进行单元测试

This separation between your model and your view needs adapter code: the ViewModel. model 和视图之间的这种分离需要适配器代码:ViewModel。 Together this is quite often abbreviated as MVVM-model.这通常被缩写为 MVVM 模型。

Back to your question回到你的问题

Your database contains several tables.您的数据库包含多个表。 Apparently you want to show some data from one of these table in a DataGridView.显然,您想在 DataGridView 中显示这些表之一中的一些数据。

The rows in the table are represented by a class.表中的行由 class 表示。 For example:例如:

class Product
{
    public int Id {get; set;}       // primary key
    public string Name {get; set;}
    public string ProductCode {get; set;}
    ...
}

Depending on what kind of method you use to access your database, your DataContext will probably have something like this:根据您用来访问数据库的方法类型,您的 DataContext 可能会有如下内容:

class DataClasses1DataContext : DbContext
{
    public DbSet<Product> Products {get; set;}
    ...
}

Where DbSet<Product> represents your database table with Products.其中DbSet<Product>表示带有 Products 的数据库表。 DbSet<Product> implements IQueryable<Product> , so you can use LINQ to fetch specific data from the table with Products. DbSet<Product>实现IQueryable<Product> ,因此您可以使用 LINQ 从带有 Products 的表中获取特定数据。

In your Form you'll need a method like this:在您的表单中,您需要这样的方法:

IEnumerable<DisplayedProduct> FetchProductsToDisplay(...)
{
    ... // TODO implement
}

If the Products in the Database are very similar to the Products that you want to Display, you don't need a separate DisplayedProduct class, if not, you need to define this class.如果数据库中的产品与您要显示的产品非常相似,则不需要单独的 DisplayedProduct class,如果不是,则需要定义此 class。

We'll first focus on how to Display fetched records in the DataGridView, later we'll look at how you fetch specific Products, for instance those that have column code 00080.我们将首先关注如何在 DataGridView 中显示获取的记录,稍后我们将了解如何获取特定的产品,例如列代码为 00080 的产品。

The View风景

You decided to display fetched Products in a DataGridView, with several columns.您决定在 DataGridView 中显示获取的产品,其中包含几列。 Usually you'll use the designer to add some columns, and to specify the format of the cells in the column.通常您会使用设计器添加一些列,并指定列中单元格的格式。 You also have to specify which column should show which property of the DisplayedProduct.您还必须指定哪一列应显示 DisplayedProduct 的哪个属性。 For this we use property DataGridViewColumn.DataPropertyName为此,我们使用属性DataGridViewColumn.DataPropertyName

columnId.DataPropertyName = nameof(DisplayedProperty.Id);
columnName.DataPropertyName = nameof(DisplayedProperty.Name);
columnProductCode.DataPropertyName = nameof(DisplayedProperty.ProductCode);
...

Now to Display the fetched products, all you have to do is assign the data to the DataGridview.DataSource现在要显示获取的产品,您只需将数据分配给DataGridview.DataSource

IEnumerable<DisplayedProduct> productsToDisplay = this.FetchProductsToDisplay(...);
this.dataGridView1.DataSource = productsToDisplay.ToList();

This will be enough to display the fetched products.这足以显示获取的产品。 However, changes that the operator makes, like adding / removing rows, or changing cells, are not reflected in the list.但是,操作员所做的更改(例如添加/删除行或更改单元格)不会反映在列表中。

If you want this, you'll have to put the fetched data into an object that implements IBindingList , like class BindingList .如果需要,您必须将获取的数据放入实现IBindingList的 object 中,例如class BindingList

Simply add a property in your form只需在表单中添加一个属性

private BindingList<DisplayedProduct> DisplayedProducts
{
    get => (BindingList<DisplayedProduct>)this.dataGridView1.DataSource;
    set => this.dataGridView1.DataSource = value;
}

Usage:用法:

private void InitDisplayedProducts()
{
    IEnumerable<DisplayedProduct> productsToDisplay = this.FetchProductsToDisplay(...);
    this.DisplayedProducts = new BindingList<DisplayedProduct>(productsToDisplay.ToList());
}

And presto, your products are displayed.很快,您的产品就会显示出来。 and all changes that the operator makes are automatically recorded, If the operator indicates that he has finished editing the products, for instance by pressing a button: you can process the changes:并且操作员所做的所有更改都会被自动记录,如果操作员表示他已经完成了对产品的编辑,例如通过按下按钮:您可以处理更改:

private void OnButtonOk_Clicked(object sender, ...)
{
    ICollection<DisplayedProducts> editedProducts = this.DisplayedProducts;
    // check which products are added / removed / changed and process them
    this.ProcessEditedProducts(editedProducts);
}

How to fetch the products that you want to display?如何获取您要展示的产品?

IEnumerable<DisplayedProduct> FetchProductsToDisplay(string productCode)
{
    using (var dbContext = new DataClasses1DataContext())
    {
        // I want only the Products with ProductCode == "00080"
        return dbContext.Products.Where(product => product.ProductCode == productCode)
            .Select(product => new DisplayedProduct
            {
                Id = product.Id,
                Name = product.Name,
                ProductCode = productCode,
                ...
            })
            .ToList();
        }
    }
}

In words: from all Products, keep only those Products that have a value for property ProductCode that equals the input parameter productCode .换句话说:从所有产品中,只保留那些具有等于输入参数productCode的属性ProductCode的值的产品。 From every remaining Product, make one new DisplayedProduct object with property values...从每个剩余的产品中,制作一个具有属性值的新 DisplayedProduct object...

If you need to process selected items, consider to add the following to your form:如果您需要处理选定的项目,请考虑将以下内容添加到您的表单中:

private DisplayedProduct CurrentProduct = (DisplayedProduct) this.dataGridView1
    .CurrentRow?.DataBoundItem

private IEnumerable<DisplayedProduct> SelectedProducts = this.dataGridView1.SelectedRows
   .Cast<DataGridViewRow>()
   .Select(row => row.DataboundItem)
   .Cast<DisplayedProduct>();

I found it:我找到了:

dataGridView1.DataSource =
        DB.W0_Calc_BedBes_UseInViews.Where(x => x.C_Code == "00080");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM