SendKeys.SendWait("{ENTER}");參考這篇,送出字串與按鈕的方法不同。
2018年4月8日 星期日
自動送出 Enter
在處理 DataGridView 編輯時,原本使用 GetChanges() 方法,取得 DataTable 中有異動的資料。
再根據其 RowState 決定要 INSERT 或 UPDATE。
但如果使用者編輯後沒有按TAB或ENTER,呼叫 GetChangs() 可能會得到 null
類似這篇
作者是參考這篇解決
測試後依然無解,最後乾脆於儲存時強行 ENTER
DataGridView 內使用 DateTimePicker
宣告全域變數
private DateTimePicker cellDateTimePicker;初始化 Form1() 時加入
this.cellDateTimePicker = new DateTimePicker(); this.cellDateTimePicker.ValueChanged += new EventHandler(cellDateTimePicker_ValueChanged); //this.cellDateTimePicker.CloseUp += new EventHandler(cellDateTimePicker_CloseUp); this.cellDateTimePicker.Format = DateTimePickerFormat.Short; this.cellDateTimePicker.ShowCheckBox = true; this.cellDateTimePicker.Checked = true; this.cellDateTimePicker.Visible = false; this.dgvCertificate.Controls.Add(cellDateTimePicker);在 ValueChanged 事件加入對應方法 (cellDateTimePicker_ValueChanged),一些屬性設定。 最後將 DateTimePicker 加入 DataGridView 的 Controls 內 撰寫 cellDateTimePicker_ValueChanged
void cellDateTimePicker_ValueChanged(object sender, EventArgs e) { if (cellDateTimePicker.Checked) { //cellDateTimePicker.Format = DateTimePickerFormat.Short; //cellDateTimePicker.CustomFormat = null; dgvCurrent.CurrentCell.Value = cellDateTimePicker.Value.ToString("yyyy/MM/dd"); //convert the date as per your format } else { //cellDateTimePicker.Checked = false; // 採用checkbox,清除值要取消勾選 //cellDateTimePicker.Format = DateTimePickerFormat.Custom; //cellDateTimePicker.CustomFormat = " "; //cellDateTimePicker.forma dgvCurrent.CurrentCell.Value = " "; } cellDateTimePicker.Visible = false; }在 DataGridView 的 CellBeginEdit 事件內加入判斷,對應的儲存格才用DateTimePicker取代
private void dgvCertificate_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { dgvCurrent = dgvCertificate; // 如果欄位是證照日期就用之前宣告的 cellDateTimePicker 取代 // 也可以用 e.ColumnIndex == 1 判斷,用 Name 避免欄位移動又得修改 if ("certificate_CER_DATE".Equals(dgvCertificate.Columns[e.ColumnIndex].Name)) { Rectangle tempRect = dgvCertificate.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); cellDateTimePicker.Location = tempRect.Location; cellDateTimePicker.Width = tempRect.Width; string s = dgvCurrent.CurrentCell.Value.ToString(); cellDateTimePicker.Value = (!"".Equals(s) && !"0001/1/1 上午 12:00:00".Equals(s)) ? DateTime.Parse(s) : DateTime.Today; cellDateTimePicker.Checked = (!"".Equals(cellDateTimePicker.Value) && !"0001/1/1 上午 12:00:00".Equals(cellDateTimePicker.Value)) ? true : false; cellDateTimePicker.Visible = true; //這行要放在所有設定之後 } }編輯結束後隱藏 DateTimePicker
private void dgvCertificate_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if ("certificate_CER_DATE".Equals(dgvCertificate.Columns[e.ColumnIndex].Name)) { cellDateTimePicker.Visible = false; } //MessageBox.Show(dgvCertificate.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()+ // dgvCertificate.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString()); }
訂閱:
文章 (Atom)