简体   繁体   English

用 C# 在我的 datagridview 的列中计算“✓”的数量

[英]Counting the number of "✓" in a column in my datagridview with C#

im really trying to figure out how to count "✓" this symbol in a column for a performance monitor.我真的想弄清楚如何在性能监视器的列中计算“✓”这个符号。 I really cannot figure out the code for this... i tried a lot of possible ways but no luck.我真的无法弄清楚这个代码......我尝试了很多可能的方法,但没有运气。 In visual basic i managed to do it but in C#,i just cant figure it out.在visual basic中我设法做到了,但在C#中,我就是想不通。

Here are some code examples that i tried.这是我尝试过的一些代码示例。

var count = dataGridView1.Rows.Cast<DataGridViewRow>()
    .Where(row => !(row.Cells[7].Value == null || row.Cells[7].Value == DBNull.Value))
    .Count();

txtSearch.Text = count.ToString();
int sum = 0;
for (int i = 0; i <= dataGridView1.Rows.Count(); i++)
{
    sum = int.Parse(dataGridView1.Rows[i].Cells[7].Value.ToString());
}
txtSearch.Text = sum.ToString();
txtSearch.Text = (from DataGridViewRow row in dataGridView1.Rows
        where row.Cells[7].FormattedValue.ToString() != string.Empty
        select Convert.ToInt32(row.Cells[7].FormattedValue)).Sum().ToString();

@demo Hello, sorry for lack of info, i kinda tried that is why is also sum, i need to count the number of times is ✓- this in that column and get the value in a textbox. @demo您好,抱歉缺少信息,我有点尝试这就是为什么也是总和,我需要计算次数是✓- 在该列中并在文本框中获取值。

@igor im posting the vb code. @igor 我正在发布 vb 代码。 also sry for the lack of info.也因为缺乏信息而感到抱歉。 Erros that i get.. usualy i get nothing.我得到的错误..通常我什么也没得到。 it just doesnt work...它只是不起作用......

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    Form15.Show()
    Dim colsum As Decimal
    Dim colsum2 As Decimal
    Dim colsum3 As Decimal
    Dim colsum4 As Decimal
    Dim colsum5 As Decimal
    Dim colsum6 As Decimal
    Dim colsum7 As Decimal
    Dim colsum8 As Decimal

    Dim a As Integer = 7
    Dim b As Integer = 8
    Dim c As Integer = 9
    Dim d As Integer = 10
    Dim x As Integer = 11
    Dim f As Integer = 12
    Dim g As Integer = 13
    Dim h As Integer = 14



    colsum = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(a).Value = "✓").Count / 20) * 100
    colsum2 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(b).Value = "✓").Count / 20) * 100
    colsum3 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(c).Value = "✓").Count / 20) * 100
    colsum4 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(d).Value = "✓").Count / 20) * 100
    colsum5 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(x).Value = "✓").Count / 20) * 100
    colsum6 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(f).Value = "✓").Count / 20) * 100
    colsum7 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(g).Value = "✓").Count / 20) * 100
    colsum8 = ((From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not Rows.IsNewRow AndAlso Rows.Cells(h).Value = "✓").Count / 20) * 100


    Form15.Label9.Text = colsum
    Form15.Label10.Text = colsum2
    Form15.Label11.Text = colsum3
    Form15.Label12.Text = colsum4
    Form15.Label13.Text = colsum5
    Form15.Label14.Text = colsum6
    Form15.Label15.Text = colsum7
    Form15.Label16.Text = colsum8

    Form15.Chart1.Series("Machine-Load").Points.AddXY("Hard-Milling", Form15.Label9.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Graphite Milling", Form15.Label10.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Wire-Cut", Form15.Label11.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Erosion", Form15.Label12.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Drilling", Form15.Label13.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Flat-Grinding", Form15.Label14.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Profile Grinding", Form15.Label15.Text)
    Form15.Chart1.Series("Machine-Load").Points.AddXY("Laser Engraving", Form15.Label16.Text)
End Sub

In programming there is a tendency to separate the data (= model) from the way that this data is displayed (= view).在编程中,倾向于将数据(= 模型)与数据的显示方式(= 视图)分开。 This has the advantage that you can change the way that you display the data without having to change the model.这样做的好处是您可以更改显示数据的方式,而无需更改 model。 So if you decide to display a checkbox instead of a check mark, your model does not have to change.因此,如果您决定显示复选框而不是复选标记,则您的 model 不必更改。

To transform the model to the view, an adapter class is needed: the ViewModel.要将 model 转换为视图,需要一个适配器 class:ViewModel。 Together these three classes are abbreviated MVVM.这三个类一起缩写为 MVVM。 Consider to read some background about this.考虑阅读有关此的一些背景知识。

In Winforms you can use the ViewModel by using the DataSource of the DataGridView.在 Winforms 中,您可以通过使用 DataGridView 的 DataSource 来使用 ViewModel。

If the data that you want display is very similar to the data in your model, you don't need a special display class.如果您要显示的数据与您的 model 中的数据非常相似,则不需要特殊的显示 class。 If the data is fairly different, it might be wise to create a special class for the Display dataSo if you want to Display Customers, you create a class DisplayCustomer:如果数据完全不同,为显示数据创建一个特殊的 class 可能是明智之举。因此,如果要显示客户,则创建一个 class 显示客户:

class DisplayCustomer
{
    public Customer Customer {get; set;}  // the Customer from the model

    public int Id
    {
        get => this.Customer.Id,
        set => this.Customer.Id = value;
    }

    public string Name
    {
        get => this.Customer.Name,
        set => this.Customer.Name = value,
    }

    ... etc.

But again: if there is no difference between the displayed data and the model data, you don't need a separate class.但同样:如果显示的数据与 model 数据没有区别,则不需要单独的 class。

A good example is your Checkmark.一个很好的例子是你的复选标记。 If this is a Boolean in Customer, but a string Checkmark in DisplayCustomer, you will have something like this:如果这是 Customer 中的 Boolean,但 DisplayCustomer 中的字符串 Checkmark,您将有如下内容:

class Customer
{
    ...
    public bool IsSpecial {get; set;}
|

class DisplayCustomer
{
    ...
    private const string checkMark = "✓";
    public string IsSpecial
    {
        get => this.Customer.IsSpecial ? checkMark : String.Empty;
        set => this.Customer.IsSpecial = checkMark == value;
    }
 

In visual studio designer you will have added your columns.在 Visual Studio Designer 中,您将添加列。 Use property DataGridViewColumn.DataPropertyName to define the name of the property that must be shown in the column.使用属性DataGridViewColumn.DataPropertyName定义必须在列中显示的属性的名称。 This can be done in the designer, or in the constructor:这可以在设计器或构造器中完成:

class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();

        this.columnId.DataPropertyName = nameof(DisplayCustomer.Id);
        this.columnName.DataPropertyName = nameof(DisplayCustomer.Name);
        ...
        this.columnIsSpecial.DataPropertyName = nameof(DisplayCustomer.IsSpecial);
    }

To Display your Customers:显示您的客户:

public BindingList<DisplayCustomer> DisplayedCustomers
{
    get => (BindingList<DisplayCustomer>)this.dataGridView1.DataSource;
    set => this.dataGridView1.DataSource = value;
}

public void DisplayCustomers()
{
    IEnumerable<Customer> customers = this.FetchCustomers();
    this.DisplayedCustomers = new BindingList<DisplayCustomer(
       customers.Select(customer => new DisplayCustomer {Customer = customer})
                .ToList());
}

That's all: two almost one liner functions make that your data is displayed, and if the operator Adds / Removes / Edits rows or cells, then the data is automatically updated.就是这样:两个几乎合一的线性函数使您的数据显示出来,如果操作员添加/删除/编辑行或单元格,则数据会自动更新。

For instance, after editing the operator presses the Apply Now button.例如,在编辑后,操作员按下立即应用按钮。

private void OnButtonApplyNow_Clicked(object sender, ...)
{
    IEnumerable<Customer> editedCustomers = this.DisplayedCustomers
        .Select(displayedCustomer => displayedCustomer.Customer);
    this.ProcessEditedCustomers(editedCustomers);
}

Counting your checkmarks is now fairly easy:计算您的复选标记现在相当容易:

private int CountCheckMarks(IEnumerable<Customer> customers)
{
    return customers.Where(customer => customer.IsSpecial).Count();
}

or if you want a property:或者如果你想要一个属性:

private int CheckMarkCount => this.DisplayedCustomers
    .Where(customer => customer.IsSpecial).Count()

Some other improvements其他一些改进

Apart from property DisplayedCustomers, you can also create properties for the Current Customer and the Selected Customers.除了属性 DisplayedCustomers,您还可以为当前客户和选定客户创建属性。

public DisplayCustomer CurrentDisplayCustomer =>
    (DisplayCustomer) this.dataGridView1.CurrentRow?.DataBoundItem;

public Customer CurrentCustomer => this.CurrentDisplayCustomer?.Customer;

public IEnumerable<DisplayCustomer> SelectedDisplayCustomers =>
    this.dataGridView1.SelectedRows.Cast<DataGridViewRow>()
        .Select(row => row.DataBoundItem)
        .Cast<DisplayCustomer>();

Once again: only create a special DisplayCustomer class if you need to.再说一遍:如果需要,只创建一个特殊的 DisplayCustomer class。

But I don't want to use the DataSource!但我不想使用数据源!

Some people prefer to directly access the DataGridViewCells.有些人喜欢直接访问 DataGridViewCells。 How about this:这个怎么样:

private const string checkMark = "✓";

private IEnumerable<DataGridViewRow> CheckedRows => this.dataGridView1.Rows
    .Cast<DataGridViewRow>()
    .Where(row => row.Cells[this.columnIsSpecial.DisplayIndex].Value.ToString() == checkMark);

private int CheckedRowCount => this.CheckedRows.Count();

I made a special property CheckedRows, because I figured you might want to use this for other purposes then to just count them.我制作了一个特殊的属性 CheckedRows,因为我想你可能想将它用于其他目的,然后只计算它们。

Thanks everyone for the help, i wish you all the best.感谢大家的帮助,我祝你一切顺利。 i Solved my problem by counting the non-empty cells in my columns.我通过计算列中的非空单元格来解决我的问题。 maybe it helps somebody else and i will post the code也许它可以帮助其他人,我会发布代码

 int count = dataGridView1.Rows
           .Cast<DataGridViewRow>()
           .Select(row => (string)row.Cells["VCE600PRO"].Value)
            .Where(v => !string.IsNullOrEmpty(v))
           .Count();

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

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