如何用于每个循环以对DataGridView中的某些字符串进行计数

问题描述 投票:0回答:1

这是我的DGV的图片:enter image description here

[您好,我正在尝试完成一个项目,在该项目中,我必须为每个循环使用a来计算某个字符串在数据网格视图中出现的时间。我已经用10个条目预先填充了DGV,并且需要计算其中有多少个条目具有“服装”作为DonType的条目。我将需要对其他DonType重新做同样的事情。

到目前为止,我所拥有的是:

int textBoxClothingCount = 0;
foreach (Donation s in donationBindingSource)
{
    textBoxClothingCount = donationBindingSource.Count("Clothing");   
}

我不确定如何指定我只想计算“衣物”捐赠的数量。 textBoxClothing计数是我在标签“衣物捐赠数量”旁边创建的只读文本框。

此外,这是在“捐赠”按钮单击内进行的,因此,每次添加捐赠时,我的只读文本框都需要自动更新。

同样,我需要为每个循环使用a。

c# datagridview datagridviewcolumn
1个回答
0
投票

同样,我需要为每个循环使用a。

您可以使用Dictionary<string, int>实现。您的OK按钮应该类似于:

{
    var dic = new Dictionary<string, int>();
    int totalValue = 0;

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        //You can replace the "DonType" and "Value" columns names with the columns indexes.
        var donType = row.Cells["DonType"].Value.ToString();

        if (dic.ContainsKey(donType))
            dic[donType] += 1;
        else
            dic.Add(donType, 1);

        totalValue += (int)row.Cells["Value"].Value;
    }

    //Update the text boxes..
    if (dic.ContainsKey("Clothing"))
        txtDonation.Text = dic["Clothing"].ToString();

    if (dic.ContainsKey("Money"))
        txtMoney.Text = dic["Money"].ToString();
    //and so forth...

    txtTotalValue.Text = totalValue.ToString();
}
© www.soinside.com 2019 - 2024. All rights reserved.