询问者
求教高手关于gridview checkbox 选中的行数据如何生成datatable?

问题
-
以前请教过本论坛的两位高手用以下一段代码把gridview转成datatable类型,但现在遇到了新问题,又得来请教各大高手了
代码如下 ,我现在的问题是需要把转换的过程过滤掉gridview 中checkbox没有被选中的行,只留下checkbox被选择中的行数据.谢谢!
考虑过两种方法实现,一种方法是用以下代码修改,从GRIDVIEW直接生成datatable,第二种方式是把gridview选中的行COPY去另一个gridview中后再调用以下方法生成datatable,但两种方式都遇到了不少困难.
public static DataTable CopyToDataTable<T>(this IEnumerable<T> array)
{
var ret = new DataTable();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
{
Type propType = dp.PropertyType;
if (propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propType = Nullable.GetUnderlyingType(propType);
}
ret.Columns.Add(dp.Name, propType);
}
foreach (T item in array)
{
var Row = ret.NewRow();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
if (dp.GetValue(item) == null)
Row[dp.Name] = DBNull.Value;
else
Row[dp.Name] = dp.GetValue(item);
//foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
// Row[dp.Name] = dp.GetValue(item);
ret.Rows.Add(Row);
}
return ret;
}
- 已编辑 hzpemu 2012年6月13日 15:19
全部回复
-
暂时找到的办法如下,但我想看看有没有用别的方法,比如用linq实现。
datatable temp2= new DataTable();
for(int i=0;i<this.GridView1.Columns.Count-1;i++)
{
temp2.Columns.Add(this.GridView1.Columns[i].HeaderText);
}foreach (GridViewRow msgRow in this.GridView1.Rows)
{
CheckBox chk = (CheckBox)msgRow.FindControl("CheckBox2");
if (chk.Checked){
//we want the GridViewRow's DataKey value
System.Data.DataRow dr = temp2.NewRow();
for (int i = 0; i < msgRow.Cells.Count-1; i++)
{
dr[i] =msgRow.Cells[i].Text.ToString();
}
temp2.Rows.Add(dr);
}
}