DataTable GridControl 数据结构
GridControl
int[] rows = this.gridView1.GetSelectedRows(); //获取选中行 gridView1
int index=gridView1.FocusedRowHandle;
//获取选中行id
string id = FRDataGridView.GetRowCellValue(index, FRDataGridView.Columns["mainid"]).ToString();
//选中行行号
int rowindex = gridView1.FocusedRowHandle;
//选中列的列号
int columnindex = gridView1.Columns.IndexOf(gridView1.FocusedColumn);
this.gridView1.GetDataRow(rowindex)[columnindex ] = "";//给选中单元格赋值
this.gridView1.GetDataRow(rowindex)["aaa"] = ""
dataGVOne.Columns[j].FieldName.ToString()
dt.Columns.Add("cmt", System.Type.GetType("System.String"));//备注
gridView1.SetFocusedValue("123");//设置单元格值:
gridView1.GetFocusedValue();//获取单元格值:
DataTable dt = ReturnDataGridView.DataSource as DataTable;//将GridControl 的DataSource转为DataTable
DataTable dt = new DataTable(); dt.Columns.Add("labelname");//增加列 dt.Columns.Add("file"); DataRow rowTable = dt.NewRow();//增加行 rowTable["labelname"] = labelname; rowTable["file"] = file; dt.Rows.Add(rowTable);
将DataTable中的某一行复制到另一个新的DataTable
方法一:直接复制一个DataTable,然后清空数据(Column结构还保留),最后再用ImportRow()方法从dt中加入需要的Row;
DataTable dt2 = new DataTable(); dt2 = dt.Copy(); dt2.Rows.Clear(); dt2.ImportRow(dt.Rows[0]);//这是加入的是第一行
例如:
int[] rows = this.gridView1.GetSelectedRows(); DataTable dt = ReturnDataGridView.DataSource as DataTable;
//将GridControl 的DataSource转为DataTable
DataTable dataTable = new DataTable(); dataTable = dt.Copy();
dataTable.Rows.Clear();
foreach (int row in rows)
{
dataTable.ImportRow(dt.Rows[row]);
//dataTable.Rows.Add(dt.Rows[row]) 将会出错:System.ArgumentException: 该行已经属于另一个表。
}
GridControl gridControl = new GridControl();
ReturnDataGridView.DataSource = dataTable;
应用:
/// <summary> /// Convert Type of List To Type of DataTable /// </summary> /// <typeparam name="T">Generic Parameter</typeparam> /// <param name="list">Collection Parameter</param> /// <returns></returns> public static DataTable ConvertToDataTable<T>(List<T> list) { DataTable dt = new DataTable(); Type t = typeof(T); PropertyInfo[] props = t.GetProperties(); if (!dataTableDic.ContainsKey(typeof(T).Name)) { foreach (var item in props) { dt.Columns.Add(item.Name, typeof(string)); } dataTableDic.Add(typeof(T).Name,dt); } else { dt = dataTableDic[typeof(T).Name]; } foreach (var item in list) { DataRow row = dt.NewRow(); for (int index = 0; index < props.Length; index++) { row[index] = props[index].GetValue(item, null); } dt.Rows.Add(row); } return dt; }
//FastReport单集合 Report report = new Report(); report.Load(@"Templates\Single.frx"); DataTable dt = TypeConverters.ConvertToDataTable<Manufacturer>(manus); dt.TableName = "Table1"; DataSet set = new DataSet(); set.Tables.Add(dt); report.RegisterData(set); report.Show();
将GridControl转化为DataTable:
//将datagridview转为datatable(仅列转换,获取架构) public DataTable GetDgvFieldNameToTable(DevExpress.XtraGrid.Views.Grid.GridView dgv) { DataTable dt = new DataTable(); // 列强制转换 for (int count = 0; count < dgv.Columns.Count; count++) { DataColumn dc; if (dgv.Columns[count].Name == "prepayColumn")//为布尔类型 { dc = new DataColumn(dgv.Columns[count].FieldName.ToString().Replace("Column", "").Replace("Col", ""), typeof(Boolean)); } else { dc = new DataColumn(dgv.Columns[count].FieldName.ToString().Replace("Column", "").Replace("Col", "")); } dt.Columns.Add(dc); } return dt; }
全选取消全选:
//全选 取消全选 private void btnselectall_Click(object sender, EventArgs e) { int count = 0; // 全选 for (int i = 0; i < detailGridView.RowCount; i++) { if (!(bool)detailGridView.GetRowCellValue(i, detailGridView.Columns["ischeck"])) { detailGridView.SetRowCellValue(i, detailGridView.Columns["ischeck"], true);//选中 } else { count++; } } //取消全选 if (count == detailGridView.RowCount) { for (int i = 0; i < detailGridView.RowCount; i++) { detailGridView.SetRowCellValue(i, detailGridView.Columns["ischeck"], false);//取消选中 } } }
遍历GridControl中的行:
DataTable dts = DGV.DataSource as DataTable; foreach (DataRow item in dts.Rows) { if (string.IsNullOrEmpty(Convert.ToString(item["color"]))) { MessageBox.Show("请", "提示"); return; } sqty += Convert.ToDecimal(item["sqty"]); spack += Convert.ToDecimal(item["spack"]); pqty += Convert.ToDecimal(item["pqty"]); ppack += Convert.ToDecimal(item["ppack"]); if (!string.IsNullOrEmpty(Convert.ToString(item["card"]))) { card += (item["card"] + ","); } else { MessageBox.Show("卡", "提示"); return; } }
遍历DataGridView中行:
foreach (datagridviewrow item in dgv.rows) { sqty += convert.todecimal(item.cells["sqty"].value); spack += convert.todecimal(item.cells["spack"].value); pqty += convert.todecimal(item.cells["pqty"].value); ppack += convert.todecimal(item.cells["ppack"].value); if (!string.isnullorempty(convert.tostring(item.cells["card"].value))) { card += (item.cells["card"].value + ","); } else { messagebox.show("卡", "提示"); return; } }
DataSet加DataTable:
DataSet ds = new DataSet(); itemTable.TableName = "itemTable"; dtproTable.TableName = "dtproTable"; commonTable.TableName = "commonTable"; ds.Tables.Add(itemTable); ds.Tables.Add(dtproTable); ds.Tables.Add(commonTable);
实际应用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
DataTable dtv = DGV.DataSource as DataTable; foreach (DataRow item in dtv.Rows) { string oldprjid = dtpro.Rows[0]["ep_productionorderid"].ToString(); string oldmcpid = dtpro.Rows[0]["ep_MakeCardPlanId"].ToString(); //retmsg += SplitPrjshtDA.SplitPro(item, dtpro, oldprjid, Convert.ToDecimal(txtlastsqty.Text), Convert.ToDecimal(txtlastspack.Text), // Convert.ToDecimal(txtlastpqty.Text), Convert.ToDecimal(txtlastppack.Text), txtdiscrip.Text, // Convert.ToInt32(gridView1.RowCount), item["card"].ToString(), // oldprjid, oldmcpid); string msg = ""; DataSet ds = new DataSet(); DataTable itemTable = new DataTable(); itemTable = dtv.Clone(); itemTable.ImportRow(item); DataTable dtproTable = new DataTable(); dtproTable = dtpro.Copy(); DataTable commonTable = new DataTable(); commonTable.Columns.Add("formproid", typeof(string)); commonTable.Columns.Add("splitorderqty", typeof(decimal)); commonTable.Columns.Add("splitorderpackageqty", typeof(decimal)); commonTable.Columns.Add("splitputgreigeqty", typeof(decimal)); commonTable.Columns.Add("splitputgreigepackageqty", typeof(decimal)); commonTable.Columns.Add("remarks", typeof(string)); commonTable.Columns.Add("splitlistqty", typeof(int)); commonTable.Columns.Add("yunshts", typeof(string)); commonTable.Columns.Add("oldproid", typeof(string)); commonTable.Columns.Add("oldmcpid", typeof(string)); //string value = HttpUtils.HttpGet("Public/InsertOrUpdateFormPrintFile", dic); DataRow dr = commonTable.NewRow(); dr[0] = oldprjid; //通过索引赋值 dr[1] = Convert.ToDecimal(txtlastsqty.Text); dr[2] = Convert.ToDecimal(txtlastspack.Text); dr[3] = Convert.ToDecimal(txtlastpqty.Text); dr[4] = Convert.ToDecimal(txtlastppack.Text); dr[5] = txtdiscrip.Text; dr[6] = Convert.ToInt32(gridView1.RowCount); dr[7] = item["card"].ToString(); dr[8] = oldprjid; dr[9] = oldmcpid; commonTable.Rows.Add(dr); itemTable.TableName = "itemTable"; dtproTable.TableName = "dtproTable"; commonTable.TableName = "commonTable"; ds.Tables.Add(itemTable); ds.Tables.Add(dtproTable); ds.Tables.Add(commonTable); string svalue = HttpUtils.HttpPost("BasicProduction/SplitPro", ds); if (!string.IsNullOrEmpty(svalue) && !svalue.Contains("failed")) { msg = JsonConvert.DeserializeObject<string>(svalue); } retmsg += msg; }
GridControl 中单元格值编辑验证:
gridView1_ValidatingEditor事件 private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e) { Regex regex = new Regex(@"^[0-9]+(\\.[0-9]*)?$"); if (gridView1.FocusedColumn.FieldName == "aaa" || gridView1.FocusedColumn.FieldName == "bbb") { if (e.Value.ToString().Length != 0) { bool result = false; result = regex.IsMatch(e.Value.ToString()); if (!result) { e.ErrorText = "请输入数值"; //单元格右下角提示 e.Valid = false; return; } } }
或者gridView1_CellValueChanging:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) { int rowindex = gridView1.FocusedRowHandle; //选中列的列号 Regex regex = new Regex(@"^[0-9]+(\\.[0-9]*)?$"); if (gridView1.FocusedColumn.FieldName == "sqty" || gridView1.FocusedColumn.FieldName == "pqty") { if (e.Value.ToString().Length != 0) { bool result = false; result = regex.IsMatch(e.Value.ToString()); if (!result) { // e.ErrorText = "请输入数值" new UserMessageBox().Show("请输入数值!", "提示"); gridView1.CloseEditor(); //e.Valid = false; return; } if (Convert.ToDouble(e.Value) <= 0) { new UserMessageBox().Show("请输入大于0的数值!", "提示"); //DGV.CancelEdit(); //e.ErrorText = "请输入大于0的数值!"; gridView1.CloseEditor(); // e.Valid = false; return; } } } else if (gridView1.FocusedColumn.FieldName == "spack" || gridView1.FocusedColumn.FieldName == "ppack") { if (e.Value.ToString().Length != 0) { bool result = false; result = regex.IsMatch(e.Value.ToString()); if (!result) { //e.ErrorText = "请输入数值"; new UserMessageBox().Show("请输入数值!", "提示"); gridView1.CloseEditor(); return; } } } }
筛选DataTabel中某些列:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#region 步骤数据表加到dtCodeList DataTable stepds = dtCodeList.Tables["CodeList"].Copy().DefaultView.ToTable(false, new string[] { "步骤名", "步骤序号","物料名称","物料编号" });//步骤名称数据表 取需要的两列 stepds.TableName = "stepds"; dtCodeList.Tables.Add(stepds);
GridControl 设置复选框:
select CAST(0 AS BIT) //sql
if(this.gridViewLeft.GetRowCellValue(rowindex,"ischeckleft").ToString() == "True")
{
this.gridViewLeft.SetRowCellValue(rowindex, "ischeckleft", false);
}
dt.Columns.Add("ischeckright", System.Type.GetType("System.Boolean"));
DataRow newRow = dt.NewRow();
newRow["ischeckright"] = Convert.ToBoolean(gridViewLeft.GetRowCellValue(i, gridViewLeft.Columns["ischeckleft"]));
dt.Rows.Add(newRow);
dgRollGridControlRight.DataSource = dt;