C#中要编辑DataGridView选中行,选中行的数据转化成实体类型(方便操作),
因为已有把 DataTable类型转为List<T>和DataRow类型转为实体。
--------------------------------------------------------------------------------------
DataGridView选中行的Row类型为DataGridViewRow,无法用转换方法,需要把DataGridViewRow转化为DataRow,才能使用 DataRow-->实体
方法一:
=====
var rowIndex = dgv_goodsList.SelectedIndex; //选中行的Row DataRow dr = (dgv_goodsList.Rows[rowIndex].DataBoundItem as DataRowView).Row; GoodsData goods = Bxlz.Common.ModelConvertHelper.GetItem<GoodsData>(dr); string str = JsonConvert.SerializeObject(goods);//把对象转换为JSON字符串 Console.WriteLine(str);
方法二:
将dataGridView选定的行转换为实体对象 (转化后为空,还在看问题)
ContactModel model = dataGridView1.CurrentRow.DataBoundItem as ContactModel;
参考:
https://social.msdn.microsoft.com/Forums/de-DE/e22e07e6-7bf7-4101-b602-0b5c46d79902/cdatarowdatagridviewrow
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); }
https://www.cnblogs.com/zzfon/p/5441144.html
获取DataGridView上选中的一行并转换为一个DataRow类型(此篇博文没有解封,在快照中看的)
DataGridViewRow gridrow = dataGridView1.SelectedRows[0]; DataRowView row_view = (DataRowView)gridrow.DataBoundItem; DataTable dt = row_view.DataView.Table.Clone();//克隆DataTable结构 dt.ImportRow(row_view.Row);//复制目标DataRow数据到新建的DataTable中