开发者

Get a collection of all the DataRows coresponding to selected DataGridView rows

Is there a direct way to do this, or do I need to iterate over the DataGridView.开发者_Go百科SelectedRows, and then access DataGridViewRow.DataBoundItem for each row to create one?


The DataGridView does not provide a SelectedDataRows and SelectedRows in not Linq-enabled, so Yes, you will have to write a foreach loop.


A generic extension method to add "SelectedDataRows" to DataGridViews:

public static T[] SelectedDataRows<T>(this DataGridView dg) where T : DataRow
{
    T[] rows = new T[dg.SelectedRows.Count];
    for (int i = 0; i < dg.SelectedRows.Count; i++)
        rows[i] = (T)((DataRowView)dg.SelectedRows[i].DataBoundItem).Row;

    return rows;
}

This is generic so that you can return a typed data row using Typed Datasets. You could make yours just return a DataRow[] if you wanted. This also assumes that your DataGridView has a DataView bound to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜