Introduction
I searched and searched the Internet for an easy way to take the rows that my users selected in a DataGrid
and insert them into a DataSet
or some other form of container that I could then make use of in my code. More specifically, when the user would sort and select multiple rows.
While I did find articles that helped, I came up short of the vision of creating an actual DataSet
. One of these articles was off of The Code Project Web site published by Chad Z. Hower aka Kudzu called "Obtaining Current DataTable Row for a DataGrid". This was helpful if my users only selected one row but did not achieve the multi-row requirement.
I am not sure how advanced or basic this really is. All I know is that my searches kept coming up short. Since I am an avid user of code that I find on the Internet, I felt it was my moral obligation to give something back and that this was my chance to do so.
Code
public static DataRow GetCurrentDataRow(DataGrid aGrid)
{
CurrencyManager xCM =
(CurrencyManager)aGrid.BindingContext[aGrid.DataSource, aGrid.DataMember];
DataRowView xDRV = (DataRowView)xCM.Current;
return xDRV.Row;
}
public static ArrayList GetSelectedRowsArray(DataGrid aGrid)
{
ArrayList al = new ArrayList();
CurrencyManager cm =
(CurrencyManager)aGrid.BindingContext[aGrid.DataSource, aGrid.DataMember];
DataView dv = (DataView)cm.List;
for(int i = 0; i < dv.Count; ++i)
{
if(aGrid.IsSelected(i))
al.Add(i);
}
return al;
}
GetSelectedRowsDataSet(DataGrid aGrid)
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
try
{
CurrencyManager cm =
(CurrencyManager)aGrid.BindingContext[aGrid.DataSource, aGrid.DataMember];
DataView dv = (DataView)cm.List;
foreach(DataColumn col in dv.Table.Columns)
{
table.Columns.Add(col.ColumnName);
}
foreach(int i in GetSelectedRowsArray(aGrid))
{
aGrid.CurrentRowIndex = i;
table.ImportRow(GetCurrentDataRow(aGrid));
}
ds.Tables.Add(table);
return ds;
}
catch (System.Exception se)
{
throw se;
}
}
Anyway, I hope this is helpful. Any ideas on how to improve would be helpful. Thanks and happy coding.
History
- 6th June, 2006: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.