将dataGridView数据转成DataTable

 

1.有数据绑定时___获取DataGridView选中行数据

  #region  获取dataGridView1选中行数据
            DataTable _dataTable = (dataGridView1.DataSource as DataTable).Clone();
            for (int i = 0 ; i < dataGridView1.SelectedRows.Count ; i++)
            {
                DataRow dr = (dataGridView1.SelectedRows[i].DataBoundItem as DataRowView).Row;
                _dataTable.Rows.Add(dr.ItemArray);
            }
 #endregion

2.无数据绑定时

public DataTable GetDgvToTable(DataGridView dgv)
        {
            DataTable dt = new DataTable();
 
            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString());
                dt.Columns.Add(dc);
            }
 
            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
      }

 

3.获取某列值( string[]  )

  string[] str = new string[dataGridView1.Rows.Count];
            for (int j ; j < dataGridView1.Rows.Count ; j++)
            {
                if (dataGridView1.Rows[j].Selected == true)
                {
                    str[j] = dataGridView1.Rows[j].Cells[1].Value.ToString();
                }
            }

 

 

 

附: DataGridView的几个基本操作:

1、获得某个(指定的)单元格的值:
  dataGridView1.Row[i].Cells[j].Value;
2、获得选中的总行数:
  dataGridView1.SelectedRows.Count;
3、获得当前选中行的索引:
  dataGridView1.CurrentRow.Index;
4、获得当前选中单元格的值:
  dataGridView1.CurrentCell.Value;

5、获取选中行的某个数据
  int a = dataGridView1.SelectedRows.Index;
  dataGridView1.Rows[a].Cells[4].Value;

6、获取当前行的某个数据

  int a=dataGridView1.CurrentRow.Index;
  string str=dataGridView1.Row[a].Cells[“strName”].Value.Tostring();

7、获得某个(指定的)单元格的值

   dataGridView1.Row[i].Cells[j].Value;

8、 取消\清空当前选择当前行某列内容

  DataGridView1.SelectedCells(0).Value.ToString();  
  DataGridView1.Rows(e.RowIndex).Cells(2).Value.ToString (); 
 

 

posted @ 2020-06-01 19:00  余路还要走多久  阅读(465)  评论(0编辑  收藏  举报