Windows窗体:将DataGridView RowCount属性绑定到标签

时间:2011-07-01 21:07:34

标签: c# data-binding gridview count label

我正在尝试将RowCount属性绑定到标签,以将DataGridView中显示的当前行数输出给用户。

我尝试了以下内容: lblArticleCount.DataBindings.Add(“Text”,datagrid,“RowCount”);

首先,似乎它将按照我想要的方式工作,但是当DataGridView更新并且其中包含更多或更少的行时,标签仍然保持不变。它不显示新的行数。

看起来我走错了路。你会如何解决它?我的目的是避免对事件作出反应,以手动将新计数设置为标签。是不是有另一种方式?

感谢。

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

为什么你不使用RowsAdded和RowsRemoved evnets来简单计算dataGridView中的行数? 检查此代码:

 public partial class Form1 : Form
{
    int rowsCount;
    public Form1()
    {
        InitializeComponent();
        dataGridView1.Columns.Add("col1", "Column 1");
        dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);
        dataGridView1.RowsRemoved += new DataGridViewRowsRemovedEventHandler(dataGridView1_RowsRemoved);
    }

    private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        rowsCount++;
        CountRows();
    }

    private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
    {
        rowsCount--;
        CountRows();
    }

    private void CountRows()
    {
        label1.Text = String.Format("Number of all rows {0}", rowsCount);
    }
}

答案 2 :(得分:-1)

这可能不是你想要的,但应该有效:

        Label showRowCount = new Label();
        DataGridView dgv = new DataGridView();
        dgv.RowsAdded += new DataGridViewRowsAddedEventHandler(dgv_RowsCountChanged);
        dgv.RowsRemoved += new DataGridViewRowsAddedEventHandler(dgv_RowsCountChanged);
    }

    void dgv_RowsCountChanged(object sender, DataGridViewRowsAddedEventArgs e)
    {
        showRowCount.Text = dgv.RowCount;
    }

答案 3 :(得分:-1)

它不起作用的原因是因为数据绑定只是一条单行道。数据绑定通常是双向绑定,其中如果UI元素更改,则通知业务对象,相反,如果更改业务对象,则UI元素更改。您似乎只实现了单向数据绑定。

相关问题