Accessing DataGridView column data as an IList

G

Guest

I have a DataGridView bound to a database query result. I would like to pick
an arbitrary column from the DataGridView and pass its data to a method that
requires it to be an IList. What is the best way to do this?
 
C

ClayB

One way you can do this is to create a wrapper DataView derived class
that implements ITypedList. Here is code that works with 2
DataGridViews dropped on a form.

namespace WindowsApplication97
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
#region Get the DataSource
DataTable dt = new DataTable("MyTable");
int nCols = 4;
int nRows = 10;
for (int i = 0; i < nCols; i++)
dt.Columns.Add(new DataColumn(string.Format("Col{0}",
i)));
for (int i = 0; i < nRows; ++i)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < nCols; j++)
{
dr[j] = string.Format("row{0} col{1}", i, j);
}
dt.Rows.Add(dr);
}
#endregion
this.dataGridView1.DataSource = dt;
this.dataGridView2.DataSource = new
MyDataViewWrapper(dt.DefaultView, "Col1");
}
}

public class MyDataViewWrapper : DataView, ITypedList
{
DataView dv;
string column;
public MyDataViewWrapper(DataView dv, string column) :
base(dv.Table)
{
this.dv = dv;
this.column = column;
}
#region ITypedList Members
PropertyDescriptorCollection
ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
{
return new PropertyDescriptorCollection(new
PropertyDescriptor[]
{ ((ITypedList)dv).GetItemProperties(listAccessors)[column] });
}
string ITypedList.GetListName(PropertyDescriptor[]
listAccessors)
{
return ((ITypedList)dv).GetListName(listAccessors);
}
#endregion
}
}

=================
Clay Burch
Syncfusion, Inc.
 
C

ClayB

In my previous post, the purpose of dataGridView2 is to show the one
arbitrary column that is from the first grid's datasource.

=====================
Clay Burch
Syncfusion, Inc.
 
G

Guest

Sorry for not responding sooner, but demands of the workload, etc...
I am intrigued by your sample here--thank you!
As my current application developed it went a different direction, but I
will keep this tip in my "active file".

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top