dgvConfig.DataSource = CreateTable();dgvConfig.Columns["編號"].ReadOnly = true; //只讀dgvConfig.AllowUserToAddRows = false; //不允許添加新行dgvConfig.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dgvConfig_EditingControlShowing);
void dgvConfig_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e){DataGridViewTextBoxEditingControl cotrol = (DataGridViewTextBoxEditingControl)e.Control;cotrol.KeyPress += new KeyPressEventHandler(Edit_Value);cotrol.MaxLength = 5;}
//DataGridView 編輯項輸入protected void Edit_Value(object sender, KeyPressEventArgs e){DataGridViewTextBoxEditingControl control = (DataGridViewTextBoxEditingControl)sender;if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar)){e.Handled = true;//消除不合適字符 }else if (Char.IsPunctuation(e.KeyChar)){if (e.KeyChar != '.' || control.Text.Length == 0)//小數點 {e.Handled = true;}if (control.Text.LastIndexOf('.') != -1){e.Handled = true;}}}
#region 輸入//允許輸入小數public static void TextBox_Double_KeyPress(object sender, KeyPressEventArgs e){TextBox tb = (TextBox)sender;if (tb == null){e.Handled = true;//消除不合適字符return;}if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar)){e.Handled = true;//消除不合適字符 }else if (Char.IsPunctuation(e.KeyChar)){if (e.KeyChar != '.' || tb.Text.Length == 0)//小數點 {e.Handled = true;}if (tb.Text.LastIndexOf('.') != -1){e.Handled = true;}}}//只能輸入整數public static void Number_KeyPress(object sender, KeyPressEventArgs e){if (e.KeyChar != '\b')//這是允許輸入退格鍵 {if ((e.KeyChar < '0') || (e.KeyChar > '9'))//這是允許輸入0-9數字 {e.Handled = true;}}}//DataGridView 編輯項輸入public static void DataGridView_Edit_Value(object sender, KeyPressEventArgs e){DataGridViewTextBoxEditingControl control = (DataGridViewTextBoxEditingControl)sender;if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar)){e.Handled = true;//消除不合適字符 }else if (Char.IsPunctuation(e.KeyChar)){if (e.KeyChar != '.' || control.Text.Length == 0)//小數點 {e.Handled = true;}if (control.Text.LastIndexOf('.') != -1){e.Handled = true;}}}#endregion
?