/// <summary> /// Allows to convert DataGridView rows to BindingSource filter /// </summary> /// <param name="bindingSource">target BindingSource</param> /// <param name="dgv">source DataGridView</param> public static void ApplyFilter(BindingSource bindingSource, DataGridView dgv) { dgv.EndEdit(); string filtertext = ""; dgv.Rows[0].Cells["AndOr"].Value = ""; foreach (DataGridViewRow row in dgv.Rows) { if (row.Cells["Field"].Value == null || row.Cells["Operator"].Value == null || row.Cells["Value"].Value == null) continue; string value = row.Cells["Value"].Value.ToString() == "@me" ? UserData.UserName : row.Cells["Value"].Value.ToString(); filtertext += string.Format("{0} {1} {2} '{3}' ", row.Cells["AndOr"].Value, row.Cells["Field"].Value, row.Cells["Operator"].Value, value); } try { bindingSource.Filter = filtertext; } catch (Exception ex) { MessageBox.Show("Invalid query\r\n" + ex.Message, "Query error"); bindingSource.Filter = string.Empty; } }
static void ckBox_CheckedChanged(object sender, EventArgs e) { dgv.EndEdit(); dgv.CurrentCell = null; bool isSelectAll = ((System.Windows.Forms.CheckBox)sender).Checked; foreach (DataGridViewRow row in dgv.Rows) { row.Cells[0].Value = isSelectAll; } if (SelectAllCheckBoxChanged != null) { SelectAllCheckBoxChanged(); } }
/// <summary> /// DataGridView添加全选 /// </summary> /// <param name="dgv">DataGridView控件ID</param> /// <param name="columnIndex">全选所在列序号</param> public void AddFullSelect(DataGridView dgv, int columnIndex) { if (dgv.Rows.Count < 1) { return; } CheckBox ckBox = new CheckBox(); Rectangle rect = dgv.GetCellDisplayRectangle(1, -1, true); ckBox.Size = new Size(dgv.Columns[1].Width - 12, 12); //大小 Point point = new Point(rect.X + 10, rect.Y + 3);//位置 ckBox.Location = point; ckBox.CheckedChanged += delegate(object sender, EventArgs e) { for (int i = 0; i < dgv.Rows.Count; i++) { dgv.Rows[i].Cells[columnIndex].Value = ((CheckBox)sender).Checked; } dgv.EndEdit(); }; dgv.Controls.Add(ckBox); }
/// <summary> /// 通用保存数据 /// </summary> /// <param name="dgv"></param> /// <param name="Typename"></param> public void ChildSavedata(DataGridView dgv,string Typename) { List<string> SqlLst = new List<string>(); int i = 0; string sysid = ""; string matid = ""; string Sql = ""; string Copynum = ""; string Memo = ""; string strsql = ""; int Count = dgv.Rows.Count; string matsysid = dgv_model.SelectedRows[0].Cells["sysid"].Value.ToString(); strsql = "delete T_ModelMats where modelsysid='" + matsysid + "' and Stype='" + Typename + "'"; SqlLst.Add(strsql); for (i = 0; i < Count-1; i++) { //先结束边界,不然不能获取当前值 dgv.EndEdit(); sysid = dgv.Rows[i].Cells["sysid"].Value.ToString(); matid = dgv.Rows[i].Cells["物料编码"].Value.ToString(); if (matid == "") continue; Copynum = dgv.Rows[i].Cells["平均复印张数"].Value.ToString(); Memo = dgv.Rows[i].Cells["备注"].Value.ToString(); Sql = "insert into T_ModelMats(modelsysid,Matid,Stype,CopyCount,memo) values " + "('" + matsysid + "','" + matid + "','" + Typename + "','" + Copynum + "','" + Memo + "') "; SqlLst.Add(Sql); } try { (new SqlDBConnect()).Exec_Tansaction(SqlLst); MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); msm_MatsSelect_(); } catch { MessageBox.Show("当前存在与该物料编码不对应的物料名,请检查后再保存!", "提示"); } }
public override void DoDefaultAction() { DataGridViewCheckBoxCell dataGridViewCell = (DataGridViewCheckBoxCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex == -1) { throw new InvalidOperationException(SR.DataGridView_InvalidOperationOnSharedCell); } if (!dataGridViewCell.ReadOnly && dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningRow != null) { dataGridView.CurrentCell = dataGridViewCell; bool endEditMode = false; if (!dataGridView.IsCurrentCellInEditMode) { endEditMode = true; dataGridView.BeginEdit(false /*selectAll*/); } if (dataGridView.IsCurrentCellInEditMode) { if (dataGridViewCell.SwitchFormattedValue()) { dataGridViewCell.NotifyDataGridViewOfValueChange(); dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex); // notify MSAA clients that the default action changed if (Owner is DataGridViewCheckBoxCell checkBoxCell) { checkBoxCell.NotifyMASSClient(new Point(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex)); } } if (endEditMode) { dataGridView.EndEdit(); } } } }
static void ckBox_CheckedChanged(object sender, EventArgs e) { try { System.Windows.Forms.DataGridView dgvParent = (System.Windows.Forms.DataGridView)(((System.Windows.Forms.CheckBox)sender).Parent); foreach (DataGridViewRow dgvr in dgvParent.Rows) { dgvr.Cells[0].Value = ((System.Windows.Forms.CheckBox)sender).Checked; if (dgvr.Cells[0].Value.ToString() == "True") { dgvParent.Rows[dgvr.Index].Selected = true; } else { dgvParent.Rows[dgvr.Index].Selected = false; } } dgvParent.EndEdit(); } catch (Exception ee) { } }
/// <summary> /// 批量删除数据 /// </summary> /// <param name="dgv"></param> /// <param name="opName">操作名</param> /// <param name="tableName">表名</param> /// <param name="key">主健</param> /// <param name="checkName">选择控件名</param> /// <param name="keyName">主键控件名</param> private void BatchDelete(DataGridView dgv, string opName, string tableName, string key, string checkName, string keyName) { if (MessageBoxEx.Show("确认要删除选择的项吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) { return; } dgv.EndEdit(); StringBuilder sbWhere = new StringBuilder(); foreach (DataGridViewRow dgvr in dgv.Rows) { object isCheck = dgvr.Cells[checkName].Value; if (isCheck != null && (bool)isCheck) { if (sbWhere.Length > 0) { sbWhere.Append(","); } string name = CommonCtrl.IsNullToString(dgvr.Cells[keyName].Value); if (name.Length > 0) { sbWhere.AppendFormat("'{0}'", name); } } } if (sbWhere.Length == 0) { DeleteDataGridViewRow(dgv, checkName); return; } if (DBHelper.BatchDeleteDataByWhere(opName, GlobalStaticObj_Server.DbPrefix + GlobalStaticObj_Server.CommAccCode, tableName, string.Format("{0} in ({1})", key, sbWhere.ToString()))) { DeleteDataGridViewRow(dgv, checkName); } else { MessageBoxEx.Show("删除失败"); } }
public void commitNewRow(DataGridView dgv) { dgv.NotifyCurrentCellDirty(true); dgv.EndEdit(); dgv.NotifyCurrentCellDirty(false); }
private void Varify(DataGridView dgv) { dgv.EndEdit(); error_privider.Clear(); string error_message = string.Empty; Dictionary<string, List<DataGridViewRow>> dicCells = new Dictionary<string, List<DataGridViewRow>>(); foreach (DataGridViewRow row in dgv.Rows) { if (row.IsNewRow) continue; row.ErrorText = string.Empty; string key = (row.Cells[0].Value + "") + "-" + (row.Cells[1].Value + "") + "-" + (row.Cells[2].Value + ""); if (key == "--") { error_message = "至少要有一個條件。\n"; continue; } if (!dicCells.ContainsKey(key)) dicCells.Add(key, new List<DataGridViewRow>()); dicCells[key].Add(row); } foreach (string key in dicCells.Keys) { if (dicCells[key].Count > 1) { error_message += "條件的組合重覆。"; } } error_privider.SetError(dgv, error_message); }
public MvcDataGridView(DataGridView dataGridView, IMvcHelper imvc) { this.iMvc = imvc; if (this.iMvc.IsRegistered) return; #region 执行控制器的子操作 Action<int, int> actExecPost = (iFlag, iCurrentRowIndex) => { if (iCurrentRowIndex > -1) this.CurrentRow = dataGridView.Rows[iCurrentRowIndex]; else this.CurrentRow = null; object oPrmValue = null; string currActionName = string.Empty; if (iFlag == 0) { currActionName = this.newActionName; oPrmValue = this.funcNewValues == null ? null : this.funcNewValues(this); } else if (iFlag == 1) { currActionName = this.editActionName; oPrmValue = this.funcEditValues == null ? null : this.funcEditValues(this); } else if (iFlag == 2) { currActionName = this.deleteActionName; oPrmValue = this.funcDeleteValues == null ? null : this.funcDeleteValues(this); } if (string.IsNullOrWhiteSpace(currActionName)) return; if (oPrmValue == null && (this.funcNewValues == null || this.funcEditValues == null || this.funcDeleteValues == null)) { if (this.CurrentRow != null) { this.iMvc.GridFirstColumnCellValue = this.GetKeyValue(); } this.iMvc.Action(currActionName); } else this.iMvc.Action(currActionName, oPrmValue); }; #endregion #region DataGridView事件与属性 dataGridView.VirtualMode = true; dataGridView.CellEnter += (s, e) => { bool isSubmited = false; //当进入单元格时,判断是否添加或编辑,则引发对应子操作 if (bNew && currChangeRowIndex != e.RowIndex) { actExecPost(0, currChangeRowIndex); //System.Diagnostics.Debug.WriteLine("new row update:" + currChangeRowIndex); isSubmited = true; } else if (currChangeRowIndex != e.RowIndex && bChged) { actExecPost(1, currChangeRowIndex); //System.Diagnostics.Debug.WriteLine("edit update:" + currChangeRowIndex); isSubmited = true; } if (isSubmited) { bChged = false; bNew = false; } }; dataGridView.CellValueChanged += (s, e) => { bChged = true; }; dataGridView.CellLeave += (s, e) => { currChangeRowIndex = e.RowIndex; }; dataGridView.Leave += (s, e) => { //当GRID失去焦点时,判断提交数据的改变,并引发对应子操作 if (bNew) { //System.Diagnostics.Debug.WriteLine("new row(leave) update:" + currChangeRowIndex); actExecPost(0, currChangeRowIndex); bNew = false; bChged = false; } if (!bChged) return; //System.Diagnostics.Debug.WriteLine("ocx update:" + currChangeRowIndex); actExecPost(1, currChangeRowIndex); bChged = false; }; dataGridView.UserAddedRow += (s, e) => { bNew = true; }; dataGridView.CancelRowEdit += (s, e) => { bNew = false; bChged = false; }; #region 行头单元格选中,切换编辑或行选中 dataGridView.CellClick += (s, e) => { if (e.RowIndex < 0) return; if (e.ColumnIndex < 0) { dataGridView.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.ClearSelection(); dataGridView.EndEdit(); dataGridView.Rows[e.RowIndex].Selected = true; return; } dataGridView.EditMode = DataGridViewEditMode.EditOnEnter; dataGridView.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect; }; #endregion dataGridView.UserDeletingRow += (s, e) => { //System.Diagnostics.Debug.WriteLine("delete:" + e.Row.Index); actExecPost(2, e.Row.Index); }; #endregion }
/// <summary> /// void UpdateGridRowCells(DataGridView _grid) /// Update the columns for the passed grid /// </summary> /// <param name="_grid"></param> public static void UpdateGridRowCells(DataGridView _grid) { try { _grid.EndEdit(); for (int n = 0; n < _grid.RowCount; n++) { for (int m = 0; m < _grid.Columns.Count; m++) { _grid.UpdateCellValue(m, n); } } } catch (Exception ex) { CommonRoutines.Log("$E:" + moduleName + ".UpdateGridRowCells > " + ex.Message); } return; }
/// <summary> /// Allows to convert datagridview to query list /// </summary> /// <param name="dgv">source</param> /// <param name="filename">path to save</param> public static void SaveQuery(DataGridView dgv, string filename) { dgv.EndEdit(); dgv.Rows[0].Cells["AndOr"].Value = string.Empty; IEnumerable queryList = dgv.Rows .Cast<DataGridViewRow>() .Where(row => row.Cells["Field"].Value != null && row.Cells["Operator"].Value != null && row.Cells["Value"].Value != null) .Select(row => new Query { AndOr = row.Cells["AndOr"].Value != null ? row.Cells["AndOr"].Value.ToString() : "", Field = row.Cells["Field"].Value.ToString(), Operator = row.Cells["Operator"].Value.ToString(), Value = row.Cells["Value"].Value.ToString() }) .ToList(); using (var sw = new StreamWriter(Path.Combine(DirectoryPath, filename), false, Encoding.Default)) { queryList.Serialize(sw); } }
private void Varify(DataGridView dgv) { dgv.EndEdit(); string error_message = string.Empty; Dictionary<string, List<DataGridViewCell>> dicCells = new Dictionary<string, List<DataGridViewCell>>(); this.errorProvider1.Clear(); if (string.IsNullOrEmpty(this.cboSemester.Text)) this.errorProvider1.SetError(this.cboSemester, "必填。"); //if (this.dgvData.Rows.Count == 0 || (this.dgvData.Rows.Count == 1 && this.dgvData.Rows[0].IsNewRow)) //{ // errorProvider1.SetError(this.dgvData, "請設定資料再儲存。"); // return; //} foreach (string key in dicCells.Keys) { if (dicCells[key].Count > 1) { dicCells[key].ForEach(x => x.ErrorText = "次別重覆。"); } } foreach (DataGridViewRow row in dgv.Rows) { if (row.IsNewRow) continue; row.Cells[0].ErrorText = ""; row.Cells[1].ErrorText = ""; row.Cells[2].ErrorText = ""; string key = row.Cells[0].Value + ""; if (!dicCells.ContainsKey(key)) dicCells.Add(key, new List<DataGridViewCell>()); dicCells[key].Add(row.Cells[0]); DateTime begin_date_time; DateTime end_date_time; if (!DateTime.TryParse(row.Cells[1].Value + "", out begin_date_time)) row.Cells[1].ErrorText = "開始時間格式錯誤。範例:2013/6/22 00:01"; if (!DateTime.TryParse(row.Cells[2].Value + "", out end_date_time)) row.Cells[2].ErrorText = "結束時間格式錯誤。範例:2013/7/31 23:59"; if (DateTime.TryParse(row.Cells[1].Value + "", out begin_date_time) && DateTime.TryParse(row.Cells[2].Value + "", out end_date_time)) { if (begin_date_time >= end_date_time) row.Cells[1].ErrorText = "開始時間不得大於或等於結束時間。"; } } foreach (DataGridViewRow row in this.dgvData.Rows) { if (row.IsNewRow) continue; DateTime begin_date_time_1; DateTime end_date_time_1; DateTime begin_date_time_2; DateTime end_date_time_2; foreach (DataGridViewRow row2 in this.dgvData.Rows) { if (row2.IsNewRow) continue; if (row.Index == row2.Index) continue; if (DateTime.TryParse(row.Cells[1].Value + "", out begin_date_time_1) && DateTime.TryParse(row.Cells[2].Value + "", out end_date_time_1) && DateTime.TryParse(row2.Cells[1].Value + "", out begin_date_time_2) && DateTime.TryParse(row2.Cells[2].Value + "", out end_date_time_2)) { if ((begin_date_time_1 >= begin_date_time_2 && begin_date_time_1 <= end_date_time_2) || (begin_date_time_2 >= begin_date_time_1 && begin_date_time_2 <= end_date_time_1)) { row.Cells[1].ErrorText = "開始時間重疊。"; row2.Cells[1].ErrorText = "開始時間重疊。"; } if ((end_date_time_1 >= begin_date_time_2 && end_date_time_1 <= end_date_time_2) || (end_date_time_2 >= begin_date_time_1 && end_date_time_2 <= end_date_time_1)) { row.Cells[2].ErrorText = "結束時間重疊。"; row2.Cells[2].ErrorText = "結束時間重疊。"; } } } } }
static void Edit(DataGridView grid, string text) { grid.BeginEdit(false); grid.EditingControl.Text = text; grid.EndEdit(); }
public static Boolean valida_vacios(DataGridView dgv, String texto) { if (dgv.Rows.Count > 0) { DataGridViewCell dgc; dgv.EndEdit(); dgc = dgv.Rows[dgv.Rows.Count - 1].Cells[texto]; if ((String)dgc.Value.ToString() == string.Empty) { MessageBox.Show("Debe tener un valor en: " + texto + ", por favor verifíquelo", "Error al llenar celdas", MessageBoxButtons.OK, MessageBoxIcon.Information); return true; } else return false; } else return false; }
/// <summary> /// /// </summary> public virtual string ParseGridAndCreateJavascriptData(DataGridView dataGridCurrent, string sJsDataTemplate, Form cMainForm, TabControl tabData) { string sReturnJavascript = sJsDataTemplate; dataGridCurrent.EndEdit(); return (sReturnJavascript); }
public void AcceptChanges(DataGridView dataGridCurrent) { if (dataGridCurrent.IsCurrentCellDirty || dataGridCurrent.IsCurrentRowDirty) { dataGridCurrent.CommitEdit(DataGridViewDataErrorContexts.Commit); } dataGridCurrent.EndEdit(); //dataGridCurrent.is //DataTable table = dataGridCurrent.DataSource as DataTable; //if (table.GetChanges() != null) //{ // foreach (DataRow row in table.Rows) // { // row.AcceptChanges(); // } //} }
/// <summary> /// 删除DataGridView选择的行 /// </summary> /// <param name="dgv">DataGridView</param> /// <param name="dgvcc">选择的复选框</param> void DeleteRow(DataGridView dgv, DataGridViewCheckBoxColumn dgvcc) { dgv.EndEdit(); for (int i = dgv.Rows.Count - 1; i >= 0; i--) { DataGridViewRow dgvr = dgv.Rows[i]; object check = dgvr.Cells[dgvcc.Name].Value; if (check != null && (bool)check) { dgv.Rows.Remove(dgvr); } } }
/// <summary> /// Додавання товарк в чек або зміна кількості товару в чеку /// </summary> /// <param name="chqDGW">Таблиця чеку</param> /// <param name="artDGW">Таблиця товарів (можливе застосування фільтру до записів)</param> /// <param name="article">Запис з товаром</param> /// <param name="startTotal">Стартова кількість</param> /// <param name="artsTable">Оригінальна таблиця товарів (без затстосування фільтру до записів)</param> public static void AddArticleToCheque(DataGridView chqDGW, DataGridView artDGW, DataRow article, double startTotal, DataTable artsTable) { //winapi.Funcs.OutputDebugString("A"); if (AppConfig.TAX_AppTaxChar == null || AppConfig.TAX_AppTaxChar.Length == 0) { MMessageBox.Show("Немає податкових ставок", "InTech PayDesk", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((double)article["PRICE"] == 0) { MMessageBox.Show("Нульова ціна товару", "InTech PayDesk", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } /* * 1) If article exist * a) CTOT=TOT * b) TOT=startValue */ //winapi.Funcs.OutputDebugString("G"); int index = 0; bool rowIsUpdated = false; DataRow dRow = null; bool funcRezult = false; DataTable cheque = chqDGW.DataSource as DataTable; if (UserConfig.Properties[9] && startTotal == AppConfig.APP_StartTotal) startTotal = CheckByMask(article["UNIT"], startTotal); //Update existed rows //winapi.Funcs.OutputDebugString("H"); if (UserConfig.Properties[7] && cheque.Rows.Count != 0) { DataRow[] dRows = cheque.Select("ID='" + article["ID"] + "'"); if (dRows.Length != 0 && dRows[0] != null) try { dRow = dRows[0]; dRow["TMPTOT"] = dRow["TOT"]; if (UserConfig.Properties[17] || startTotal == 0.0) { Request req = new Request(dRow, startTotal); funcRezult = req.UpdateRowSource(chqDGW); req.Dispose(); //winapi.Funcs.OutputDebugString("U"); if (!funcRezult) return; } else dRow["TOT"] = GetRoundedDose(startTotal); index = cheque.Rows.IndexOf(dRow); rowIsUpdated = true; } catch (Exception ex) { WriteLog(ex, MethodInfo.GetCurrentMethod().Name); } } //Add new row if (!rowIsUpdated) { //winapi.Funcs.OutputDebugString("J"); dRow = cheque.NewRow(); dRow["ORIGPRICE"] = article["PRICE"]; //C string c = dRow["C"].ToString(); dRow.ItemArray = article.ItemArray; dRow["C"] = long.Parse(c); //TAX try { index = Array.IndexOf<char>(AppConfig.TAX_MarketColumn, dRow["VG"].ToString()[0]); } catch { index = 0; } if (index < 0) index = 0; char pch = AppConfig.TAX_AppColumn[index]; index = Array.IndexOf<char>(AppConfig.TAX_AppTaxChar, pch); if (index >= 0) { dRow["VG"] = pch; dRow["TAX_VAL"] = AppConfig.TAX_AppTaxRates[index]; dRow["USEDDISC"] = AppConfig.TAX_AppTaxDisc[index]; } if (UserConfig.Properties[17] || startTotal == 0.0) { Request req = new Request(dRow, startTotal); funcRezult = req.UpdateRowSource(chqDGW); req.Dispose(); if (!funcRezult) return; } else dRow["TOT"] = startTotal; #region Sorting article by ID and adding if (UserConfig.Properties[14] && cheque.Rows.Count != 0) { index = 0; do { if (GetIDCode(cheque.Rows[index]["ID"]) < GetIDCode(dRow["ID"])) index++; else break; } while (cheque.Rows.Count > index); cheque.Rows.InsertAt(dRow, index); } else { cheque.Rows.Add(dRow); index = cheque.Rows.Count - 1; } #endregion } //winapi.Funcs.OutputDebugString("K"); if (rowIsUpdated) index = dRow.Table.Rows.IndexOf(dRow); chqDGW.CurrentCell = chqDGW.Rows[index].Cells["TOT"]; try { object uniqueKey = article["C"]; article = (artDGW.DataSource as DataTable).Rows.Find(uniqueKey); if (article != null) index = (artDGW.DataSource as DataTable).Rows.IndexOf(article); else { artDGW.DataSource = artsTable; article = artsTable.Rows.Find(uniqueKey); index = artsTable.Rows.IndexOf(article); } artDGW.CurrentCell = artDGW.Rows[index].Cells[artDGW.Columns.GetFirstColumn(DataGridViewElementStates.Visible).Name]; } catch { } chqDGW.BeginEdit(true); if (!UserConfig.Properties[22]) chqDGW.EndEdit(); //winapi.Funcs.OutputDebugString("E"); }
private void SetCellValue(DataGridView dataGridView, int rowIndex, int columnIndex, object value) { dataGridView.CurrentCell = dataGridView.Rows[rowIndex].Cells[columnIndex]; dataGridView.BeginEdit(true); dataGridView.CurrentCell.Value = value; dataGridView.EndEdit(); }