Windows Forms: Binding DataGridView RowCount property to a label
I'm try开发者_JAVA技巧ing to bind the RowCount property to a label to output the current number of rows displayed in the DataGridView to the user.
I tried the following: lblArticleCount.DataBindings.Add("Text", datagrid, "RowCount");
First it seems like that it is gonna working exactly the way I want but when the DataGridView gets updated and more or less rows are in it, the label still stays the same. It does not display the new count of rows.
Looks like I'm on the wrong way. How would you solve it? My aim was to avoid to react to events to set the new count to the label manually. Isn't there another way?
Thanks.
Why you dont simply count the number of rows in dataGridView, using RowsAdded and RowsRemoved evnets? Check this code:
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);
}
}
You must implement http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
This is probably not what you intend, but it should work:
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;
}
The reason that it is not working is because the data-binding is only a one-way street. Databinding is typically a two-way binding where if a UI element changes, then the business object is notified and conversely, if a business object is changed, then the UI element changes. It seems like you have only implemented a one-way data-binding.
精彩评论