在标签中的datagridview中添加行的总和

时间:2017-03-22 10:08:30

标签: c# winforms datagridview label

我有一个标签作为字幕,在这个标签中我想显示datagridview中的行数。

我添加了这行代码,但它只返回0而不是datagridview中的行数。

 private void Form_Load(object sender, EventArgs e)
 {
        lblTitle.Text = _settings.set;
        lblSubtitle.Text = dataGridView1.RowCount.ToString();
 }

为什么它只显示0?

2 个答案:

答案 0 :(得分:1)

  1. 要求
  2. DataGridView
  3. 选择要汇总的列名
  4. 保存结果的标签需要
  5. SelectAmount是Label

    private void function()   {

            int SelectResult = 0;
            if (DataSelector.RowCount != 0)
            {
                for (int i = 0; i < DataSelector.RowCount; i++)
                {
                    bool value = false;
                    if (DataSelector.Rows[i].Cells["Select"].Value != null)
                    {
                        value = (bool)DataSelector.Rows[i].Cells["Select"].Value;
                        if (value)
                        {
    
                               int ar = 0;
                               bool r = int.TryParse(DataSelector.Rows[i].Cells["Paid"].Value.ToString(), out ar);
                                if (r)
                                {
                                    SelectResult += ar;
                                }
                        }
    
                    }
                }
    
            }
                SelectAmount.Text = SelectResult.ToString();
    }
    

答案 1 :(得分:1)

使用RowsAddedRowsRemoved事件更新带有新值的标签

public class YourForm
{
    public YourForm()
    {
        InitializeComponent();

        UpdateSubtitle(); // Display initial value

        dataGridView1.RowsAdded += (sender, args) => UpdateSubtitle();
        dataGridView1.RowsRemoved += (sender, args) => UpdateSubtitle();
    }

    private void UpdateSubtitle()
    {
        lblSubtitle.Text = dataGridView1.RowCount.ToString();
    }
}