When I open my form, I’m adding a bunch of rows to a DataSet that is bound to a DataGridView. Later on, when I’m enumerating the rows in my DataGridView, I’d like to have access to some of the data that was used to populate the DataSet but is not stored in the DataSet proper.
Something like this:
public void OnStartup()
{
foreach (var data in GetData())
{
var row = MyDataSet.MyTable.AddRow(data.Value);
// here's the part where I'm not sure what to do.. ideally:
row.GetDataGridViewRow().Tag = data.Metadata;
}
}
public void LaterOn()
{
foreach (var row in MyDataGridView.GetSelected())
{
var metadata = (Metadata)row.Tag; // or something
...
}
}
What is the best way to attach some metadata to a DataSet or DataGridView row?
I would say that this is one of those situations where there is no single ‘right’ way of doing it, just a matter of choosing an approach on a case by case basis.
There is nothing wrong with using the
DataGridViewTagproperty like this. Indeed, that is it’s purpose, as stated on MSDN:One alternative that I would consider is to use a
BindingList<T>with custom backing objects as theDataSourcerather than aDataSetand store the meta data in the backing objects. You can then access each object using theDataGridViewRow‘sDataBoundItemproperty.I would marginally favour this way since it keeps the data and the UI a little more separated and means you can grab the meta data even when you only have the backing object, but I doubt that there is any concrete difference in terms of performance or memory usage.