将DataGridView中的行对象(DataGridViewRow)转为DataTable的行对象(DataRow)

来源:互联网 发布:元彬在韩国的地位知乎 编辑:程序博客网 时间:2024/04/25 19:50

有时候我们需要将DataGridView中选择的行存为一个DataTable,这时候就要将DataGridViewRow对象转为DataRow对象。具体做法如下:

 

            DataGridViewSelectedRowCollection  rowColl = dataGridView1.SelectedRows;

 

            if (rowColl  == null)

                return;

 

            DataTable totalDT = (DataTable)dataGridView1.DataSource;

            if (totalDT == null)

                return;

 

            DataTable gridSelectDT = totalDT.Clone();

 

            for (int i = 0; i < rowColl .Count; i++)

            {

 

                DataRow dataRow = (rowColl[i].DataBoundItem as DataRowView).Row; 

                gridSelectDT.ImportRow(dataRow);

            }