private void btnUpdate_Click(object sender, System.EventArgs e) { if (lstClips.SelectedItem != null && !lstClips.Enabled) { Clip theClip = (Clip)lstClips.SelectedItem; foreach (Clip otherClip in _clips.TextClips) { if (otherClip != theClip && otherClip.Name == txtClipName.Text) { errorProvider.SetIconAlignment(txtClipName, ErrorIconAlignment.MiddleLeft); errorProvider.SetError(txtClipName, "Must have a unique clip name"); return; } } theClip.Name = txtClipName.Text; theClip.Content = txtClipText.Text; errorProvider.SetError(txtClipName, ""); enableButtons(false); // Force reset of clip data... lstClips.Items[lstClips.SelectedIndex] = theClip; _clips.Modified = true; } }
private bool validateOrgAccount() { if (this.textBox1.Text.Length == 0) { AM_Controls.MsgBoxX.Show("Заполните поле Р./СЧЁТ", "BPS", MessageBoxButtons.OK, MessageBoxIcon.Warning); this.textBox1.Focus(); return(false); } if (this.textBox1.Text.Length != 20) { AM_Controls.MsgBoxX.Show("Р.счёт должен содержать 20 цифр!", "BPS", MessageBoxButtons.OK, MessageBoxIcon.Warning); err.SetError(textBox1, "Р.счёт должен содержать 20 цифр!"); this.textBox1.Focus(); return(false); } err.SetError(textBox1, ""); if (this.cmbBank.SelectedIndex == -1) { AM_Controls.MsgBoxX.Show("Выберите БАНК", "BPS", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } if (this.cmbCurr.SelectedIndex == -1) { AM_Controls.MsgBoxX.Show("Выберите ВАЛЮТУ", "BPS", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } return(true); }
private void btnSet_Click(object sender, EventArgs e) { try { string errMsg = GenericQbItem.ValidateText(typeof(string), typeof(string), txtItem.Text); if (errMsg.Length != 0) { err.SetError(txtItem, errMsg); } else { try { lstItems.BeginUpdate(); int idx = getSelectedItem(); _preventUpdate = true; lstItems.Items[idx] = ""; //force item to update, if only case has changed it won't update lstItems.Items[idx] = txtItem.Text; } finally { _preventUpdate = false; lstItems.EndUpdate(); } } } catch (Exception ex) { base.ShowException("Script Set Item Error", ex); } }
private void SlopeValidate(object sender, CancelEventArgs e) { Debug.Assert(sender == txtSlope, "SlopeValidate method called by wrong control"); try { int slope = int.Parse(txtSlope.Text); if (slope < MinSlope || slope > MaxSlope) { err.SetError(txtSlope, "Slope must be between 55 and 155"); e.Cancel = true; } } catch { err.SetError(txtSlope, "BUG: Slope must be an integer"); e.Cancel = true; } if (e.Cancel) { txtSlope.SelectAll(); } else { err.SetError(txtSlope, ""); } }
private bool ValidInput() { try { int port = Convert.ToInt32(txtPort.Text); if (port <= 0 || port > 65535) { throw new Exception("Invalid Port"); } } catch (Exception) { errorProvider.SetError(txtPort, "Invalid Port Number"); return(false); } errorProvider.SetError(txtPort, string.Empty); if (radListenSpecific.Checked) { if (comInterfaces.SelectedItem == null) { errorProvider.SetError(comInterfaces, "Select a valid interface"); return(false); } } errorProvider.SetError(comInterfaces, string.Empty); return(true); }
//validate the textWidth field private void textWidth_Validated(object sender, System.EventArgs e) { int fieldValue; //Check to see if user entered a valid integer value if (int.TryParse(textWidth.Text, out fieldValue)) { //The value is an integer if (fieldValue < 24 || fieldValue > 96) { this.textWidth.Select(0, textWidth.Text.Length); textWidthErrorProvider.SetError(this.textWidth, "Must be between 24 and 96"); } else { textWidthErrorProvider.SetError(this.textWidth, String.Empty); } } else { //The value is not an integer textWidthErrorProvider.SetError(this.textWidth, "Not a valid integer."); } }
private void btnReset_Click(object sender, System.EventArgs e) { if (cmbUsuarios.SelectedItem != null) { if (txtNewPass.Text != txtOtraVez.Text) { epFrmReset.SetError(txtNewPass, "Las Passwords deben coincidir..."); epFrmReset.SetError(txtOtraVez, "Las Passwords deben coincidir..."); } else { epFrmReset.SetError(txtNewPass, ""); epFrmReset.SetError(txtOtraVez, ""); if (MessageBox.Show("Esta a punto de cambiar la password del usuario:" + Environment.NewLine + cmbUsuarios.SelectedValue.ToString(), "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes) { if (CambiarPassword(cmbUsuarios.SelectedValue.ToString(), txtNewPass.Text)) { MessageBox.Show("La nueva password fue guardada con exito", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No se pudo cambiar la password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Cancelar(); } } else { Cancelar(); } } } }
private void Txt_barcode_Leave(object sender, EventArgs e) { if (Check_barcode() == false && count == 0) { count++; // מגדירים שגאיה בהתאם barcodeErrorProvider = new ErrorProvider(); barcodeErrorProvider.SetError(Txt_barcode, "ברקוד מכיל 13 או 12 ספרות"); } else { if (Check_barcode() == true && count == 0) { //לא מבצעים פעולות // נשאר count=0 } else { if (Check_barcode() == true) { barcodeErrorProvider.SetError(Txt_barcode, ""); } else { barcodeErrorProvider.SetError(Txt_barcode, "ברקוד מכיל 13 או 12 ספרות"); } } } }
private void txt_Validating(Object sender, System.ComponentModel.CancelEventArgs e) { // Convert the control to the appropriate data type Control ctrl = (Control)sender; // Clear the error provider epValidation.SetError(ctrl, ""); // Set up the appropriate column DataColumn dcCust = null; if (ctrl.Name == txtName.Name) { dcCust = m_dsCustomer.Tables[Customer.TN_CUSTOMER].Columns[Customer.FN_CUSTOMER_NAME]; } if (ctrl.Name == txtPostalCode.Name) { dcCust = m_dsCustomer.Tables[Customer.TN_CUSTOMER].Columns[Customer.FN_POSTALCODE]; } // Perform the validation // In order to pass the value in by reference, it needs to be in a variable string sControlText = ctrl.Text; string sErrorText = ValidationUtility.ValidateColumn(ref sControlText, dcCust); //If the value was changed, need to reassign to the control ctrl.Text = sControlText; // If there was an error, assign it to the error provider if (sErrorText.Length != 0) { epValidation.SetError(ctrl, sErrorText); } }
private void phoneNumberTBox_Leave(object sender, EventArgs e) { // בודקים תקינות קלט if (check_phone_number() == false && count == 0) { count++; phoneErrorProvider = new ErrorProvider(); phoneErrorProvider.SetError(phoneNumberTBox, "מספר פלאפון חייב להכיל בדיוק 10 ספרות"); } else { if (check_phone_number() == true && count == 0) { //לא מבצעים פעולות // נשאר count=0 } else { if (check_phone_number() == true) { phoneErrorProvider.SetError(phoneNumberTBox, ""); } else { phoneErrorProvider.SetError(phoneNumberTBox, "מספר פלאפון חייב להכיל בדיוק 10 ספרות"); } } } }
private void ShowIncubateProcessingTimeError() { errorIncubateProcessingTime.SetIconAlignment( txtIncubateProcessingTime, ErrorIconAlignment.MiddleLeft); errorIncubateProcessingTime.SetError( txtIncubateProcessingTime, "Incubate processing time must be >= 0"); }
private void btnSave_Click(object sender, EventArgs e) { ErrorProvider errorProvider1 = new ErrorProvider(); if (string.IsNullOrWhiteSpace(this.txtSubject.Text)) { errorProvider1.SetError(this.txtSubject, "必填。"); return; } else errorProvider1.SetError(this.txtSubject, ""); try { this.btnSave.Enabled = false; conf.Content = webBrowser1.Document.Body.InnerHtml.Replace("<div id=\"editable\">", string.Empty); conf_subject.Content = this.txtSubject.Text.Trim(); List<ActiveRecord> recs = new List<ActiveRecord>(); recs.Add(conf); recs.Add(conf_subject); (new AccessHelper()).UpdateValues(recs); MessageBox.Show("儲存成功。"); //this.Close(); } catch (Exception ex) { MsgBox.Show(ex.Message); } finally { this.btnSave.Enabled = true; } }
private bool ValidateInput() { if (txtURL.Text.Length == 0) { erProvider.SetError(txtURL, "Please enter a URL"); return(false); } if (txtUsername.Text.Length == 0) { erProvider.SetError(txtUsername, "Please enter a username"); return(false); } if (txtPassword.Text.Length == 0) { erProvider.SetError(txtPassword, "Please enter a password"); return(false); } try { new Uri(txtURL.Text); } catch (Exception) { erProvider.SetError(txtURL, "Invalid URL specified"); return(false); } return(true); }
private void Busqueda() { if (txt_Busqueda.Text.Trim() == "") { errorProvider1.SetError(txt_Busqueda, "No puedes dejar el campo vacio"); MessageBox.Show("Inserta todos los datos marcados", "Error de datos insertados", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { OleDbConnection con = new OleDbConnection(); OleDbCommand coman = new OleDbCommand(); OleDbDataReader dr; con.ConnectionString = ObtenerString(); coman.Connection = con; string busqueda = txt_Busqueda.Text; txt_Busqueda.Text = busqueda.ToUpper(); coman.CommandText = "Select * from Tb_TipoPieza where (Nombre='" + busqueda.ToUpper() + "'OR Lote='" + busqueda.ToUpper() + "') AND Activo='S'"; coman.CommandType = CommandType.Text; con.Open(); data_resultado.Rows.Clear(); dr = coman.ExecuteReader(); while (dr.Read()) { int Renglon = data_resultado.Rows.Add(); Idp = dr.GetInt32(dr.GetOrdinal("Id_TipoPieza")); data_resultado.Rows[Renglon].Cells["Id"].Value = dr.GetInt32(dr.GetOrdinal("Id_TipoPieza")); data_resultado.Rows[Renglon].Cells["Nombre"].Value = dr.GetString(dr.GetOrdinal("Nombre")); data_resultado.Rows[Renglon].Cells["Lote"].Value = dr.GetString(dr.GetOrdinal("Lote")); data_resultado.Rows[Renglon].Cells["Descripcion"].Value = dr.GetString(dr.GetOrdinal("Descripcion")); } con.Close(); } }
private void button1_Click(object sender, EventArgs e) { ErrorProvider erro = new ErrorProvider(); if(TitulotextBox.Text.Length == 0 || DescripcionrichTextBox.Text.Length == 0) { erro.SetError(TitulotextBox,"No puede dejar este campo vacio"); erro.SetError(DescripcionrichTextBox,"Debe llenar este campo"); } else { Pelicula p = new Pelicula(); p.Titulo = TitulotextBox.Text; p.Descripcion = DescripcionrichTextBox.Text; int resultado = PeliculaConexion.Agregar(p); if(resultado > 0) { MessageBox.Show("Se guardo la Pelicula", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); TitulotextBox.Text = ""; DescripcionrichTextBox.Text = ""; } else { MessageBox.Show("No se pudo guardar la pelicula", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private void ShowIterationsCountError() { errorIterationsCount.SetIconAlignment( txtIterationsCount, ErrorIconAlignment.MiddleLeft); errorIterationsCount.SetError( txtIterationsCount, "Iterations count must be >= 1"); }
private void ValidNumber_Validating(object sender, System.ComponentModel.CancelEventArgs e) { string myMessage = ""; if (Text == "") { errorProvider1.SetError(this, myMessage); //sets no error message. (empty is OK) return; } try{ if (System.Convert.ToInt32(this.Text) > MaxVal) { throw new Exception("Number must be less than " + (MaxVal + 1).ToString()); } if (System.Convert.ToInt32(this.Text) < MinVal) { throw new Exception("Number must be greater than or equal to " + (MinVal).ToString()); } errorProvider1.SetError(this, ""); } catch (Exception ex) { if (ex.Message == "Input string was not in a correct format.") { myMessage = "Must be a number. No letters or symbols allowed"; } else { myMessage = ex.Message; } } errorProvider1.SetError(this, myMessage); }
private void ShowCommandExtensionTimeError() { errorCommandExtensionTime.SetIconAlignment( txtCommandExtensionTime, ErrorIconAlignment.MiddleLeft); errorCommandExtensionTime.SetError( txtCommandExtensionTime, "Command extension time must be >= 0"); }
private void comboDestDir_TextChanged(object sender, System.EventArgs e) { buttonCheck.Enabled = buttonGo.Enabled = false; // check if (!System.IO.Directory.Exists(comboDestDir.Text)) { // directory not found errorProvider.SetError(comboDestDir, "保存先フォルダが見つかりません。"); } else if (!FileUtility.IsNTFS(comboDestDir.Text)) { // not ntfs errorProvider.SetError(comboDestDir, "バックアップ保存先がNTFSボリュームではありません。"); } else { // ok errorProvider.SetError(comboDestDir, ""); labelPrevDir.Text = "前回バックアップ: " + Dumper.GetPreviousSnap( comboDestDir.Text, DateTime.Now, (Int32)numericLimitDay.Value); if (errorProvider.GetError(comboBackupDir) == "") { buttonCheck.Enabled = buttonGo.Enabled = true; } } }
//---------------- check data input before change --------------- private bool ValidateChangeInput() { ep.SetError(txtOldCustCode, ""); ep.SetError(txtNewCustCode, ""); if (txtOldCustCode.Text.Trim().Length == 0) { ep.SetError(txtOldCustCode, clsResources.GetMessage("errors.required", txtOldCustCode.Text)); txtOldCustCode.Focus(); return(false); } else if (txtNewCustCode.Text.Trim().Length == 0) { ep.SetError(txtNewCustCode, clsResources.GetMessage("errors.required", txtNewCustCode.Text)); txtNewCustCode.Focus(); return(false); } else if (!ValidateNumber(txtNewCustCode.Text)) { MessageBox.Show("New customer code must be numeric and not any space !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtNewCustCode.Focus(); return(false); } return(true); }
/*private void ValidDouble_Validating(object sender, System.ComponentModel.CancelEventArgs e) { * string myMessage=""; * try{ * if(Text==""){ * errorProvider1.SetError(this,""); * return;//Text="0"; * } * if(System.Convert.ToDouble(this.Text)>MaxVal) * throw new Exception("Number must be less than "+(MaxVal+1).ToString()); * if(System.Convert.ToDouble(this.Text)<MinVal) * throw new Exception("Number must be greater than or equal to "+(MinVal).ToString()); * errorProvider1.SetError(this,""); * } * catch(Exception ex){ * if(ex.Message=="Input string was not in a correct format."){ * myMessage="Must be a number. No letters or symbols allowed"; * } * else{ * myMessage=ex.Message; * } * errorProvider1.SetError(this,myMessage); * } * }*/ private void ValidDouble_TextChanged(object sender, EventArgs e) { string myMessage = ""; try { if (Text == "") { errorProvider1.SetError(this, ""); return; //Text="0"; } if (System.Convert.ToDouble(this.Text) > MaxVal) { throw new Exception("Number must be less than " + (MaxVal + 1).ToString()); } if (System.Convert.ToDouble(this.Text) < MinVal) { throw new Exception("Number must be greater than or equal to " + (MinVal).ToString()); } errorProvider1.SetError(this, ""); } catch (Exception ex) { if (ex.Message == "Input string was not in a correct format.") { myMessage = "Must be a number. No letters or symbols allowed"; } else { myMessage = ex.Message; } errorProvider1.SetError(this, myMessage); } }
private void txtFileName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { string error = ""; // Check assembly file name has been entered string assemFileName = Path.GetFileName(txtFileName.Text); if (assemFileName == "") { error = "FileName can't be empty."; e.Cancel = true; errorProvider.SetError(txtFileName, error); return; } // Check that folder is valid string assemDir = Path.GetDirectoryName(txtFileName.Text); if (assemDir != "") { if (!Directory.Exists(assemDir)) { error = string.Format("Folder {0} does not exist.", assemDir); e.Cancel = true; errorProvider.SetError(txtFileName, error); return; } } errorProvider.SetError(txtFileName, error); }
private void ShowSeparationProcessingTimeError() { errorSeparationProcessingTime.SetIconAlignment( txtSeparationProcessingTime, ErrorIconAlignment.MiddleLeft); errorSeparationProcessingTime.SetError( txtSeparationProcessingTime, "Separation processing time must be >= 0"); }
// User clicked OK private void button1_Click(object sender, System.EventArgs e) { bool bFieldsValid = true; // Check to make sure that required fields are filled in. // Set error provider control to signal errors to the user if they're not. if (textBox1.Text.Length == 0) { errorProvider1.SetError(textBox1, "A UserID is required"); bFieldsValid = false; } else { errorProvider1.SetError(textBox1, ""); } if (textBox2.Text.Length == 0) { errorProvider1.SetError(textBox2, "A Password is required"); bFieldsValid = false; } else { errorProvider1.SetError(textBox2, ""); } // Fire event to container if they are. if (bFieldsValid == true) { OkClicked(textBox1.Text, textBox2.Text); } }
private void submitClick(object sender, System.EventArgs e) { bool emptyDetected = false; if (LastNameBox.Text.Length == 0) { submitError.SetError(LastNameBox, "Please enter last name"); emptyDetected = true; } else { submitError.SetError(LastNameBox, ""); } if (AccountNumberBox.Text.Length == 0) { submitError.SetError(AccountNumberBox, "Please enter account number"); emptyDetected = true; } else { submitError.SetError(AccountNumberBox, ""); } if (emptyDetected) { return; } refDo.LastName = this.LastNameBox.Text; refDo.AccountNumber = int.Parse(this.AccountNumberBox.Text); refDo.ValidAccountNumber = true; // MessageBox.Show(refDo.toString()); this.Close(); }
/// <summary> /// Resets all of the errorproviders when anything succeeds /// </summary> private void ResetAllErrProviders() { foreach (Control ctl in this.Controls) { errorProvider.SetError(ctl, ""); } }
private void OnValidatingAddress(AddressValidatingEventArgs e) { if (ValidatingAddress != null) { ValidatingAddress(this, e); errInvalid.SetError(this.ValidateButton, e.ErrorMessage); } }
private void inputText_Validating(object sender, System.ComponentModel.CancelEventArgs e) { errorProvider1.SetError(inputText, ""); if (inputText.Text.Trim() == "") { errorProvider1.SetError(inputText, "Entry cannot be empty"); e.Cancel = true; } }
private void Scalevalue_ok_Click(object sender, EventArgs e) { //put validation here panel1.Invalidate(); panel1.Update(); ErrorProvider error = new ErrorProvider(); error_Label.Text = "..."; if (real_length1.Text == "") { error.SetError(real_length2, "Scale Value cannot be empty"); error_Label.Text = "Scale Value cannot be empty"; return; } else { error.SetError(real_length2, ""); } if (Convert.ToInt32(real_length1.Text) == 0) { error.SetError(real_length2, "Enter Proper Scale Value(Scale Value cannot be null or Zero)"); error_Label.Text = "Scale Value cannot be Zero"; return; } else { error.SetError(real_length2, ""); } if (unit_combobox.SelectedIndex == 0) { error.SetError(unit_combobox, "Select the unit"); error_Label.Text = "Select the unit (cm,metre,feet)"; return; } else { error.SetError(unit_combobox, ""); } double scale_calculated = Convert.ToInt32(real_length1.Text.ToString())/pixelvalue; ImagePropertiesClass.scale_value = (float)Math.Round(scale_calculated,2); ImagePropertiesClass.scale_set = true;//now the scale is set for the loaded image ImagePropertiesClass.scale_unit = this.unit_combobox.SelectedItem.ToString();//returns the selected index(unit) Console.WriteLine("Value of the Scale is:" + ImagePropertiesClass.scale_value); //enter value in db Commonforallfunctions.set_scalepoints(); ProjectClass.db_cmd.CommandText = "UPDATE images set scale=@scale ,scale_x1=@scale_x1,scale_y1=@scale_y1,scale_x2=@scale_x2,scale_y2=@scale_y2 ,scale_unit=@scale_unit where iid=" + ImagePropertiesClass.ImageId + ";"; ProjectClass.db_cmd.Parameters.AddWithValue("@scale", ImagePropertiesClass.scale_value); ProjectClass.db_cmd.Parameters.AddWithValue("@scale_x1",ImagePropertiesClass.scale_startpt.X ); ProjectClass.db_cmd.Parameters.AddWithValue("@scale_y1", ImagePropertiesClass.scale_startpt.Y); ProjectClass.db_cmd.Parameters.AddWithValue("@scale_x2", ImagePropertiesClass.scale_endpt.X); ProjectClass.db_cmd.Parameters.AddWithValue("@scale_y2", ImagePropertiesClass.scale_endpt.Y); ProjectClass.db_cmd.Parameters.AddWithValue("@scale_unit",ImagePropertiesClass.scale_unit); ProjectClass.db_cmd.ExecuteNonQuery(); this.Dispose(); }
private void txt_barcode_Leave(object sender, EventArgs e) { // בודקים אם לקוח קיים לפי תעודת זהות if (txt_barcode.Text != "") { //product Prod = new product(); Product[] Product = mySQL.GetProductData(); string temporary_barcode = txt_barcode.Text; for (int i = 0; i < Product.Length; i++) { if (temporary_barcode == Product[i].Barcode.ToString()) { MessageBox.Show("מוצר קיים , ניתן להוסיף כמות"); load_products = mySQL.GetProductDataByBarcode(txt_barcode.Text); txt_barcode.Text = load_products.Barcode.ToString(); txt_category.Text = load_products.Category.ToString(); txt_model.Text = load_products.Model.ToString(); txt_manufacturer.Text = load_products.Manufacturer.ToString(); txt_supplier.Text = load_products.Supplier.ToString(); txt_costPrice.Text = load_products.Cost_price.ToString(); txt_sellingPrice.Text = load_products.Selling_price.ToString(); //productAmount.Value = load_products.Amount; txt_productInformation.Text = load_products.Product_info.ToString(); Read_only_true(); } } } if (Check_barcode() == false && count == 0) { count++; // מגדירים שגאיה בהתאם barcodeErrorProvider = new ErrorProvider(); barcodeErrorProvider.SetError(txt_barcode, "ברקוד מכיל 13 או 12 ספרות"); } else { if (Check_barcode() == true && count == 0) { //לא מבצעים פעולות // נשאר count=0 } else { if (Check_barcode() == true) { barcodeErrorProvider.SetError(txt_barcode, ""); } else { barcodeErrorProvider.SetError(txt_barcode, "ברקוד מכיל 13 או 12 ספרות"); } } } }
private void ValidDate_Validating(object sender, System.ComponentModel.CancelEventArgs e) { string myMessage = ""; try{ if (Text == "") { errorProvider1.SetError(this, ""); return; } bool allNums = true; for (int i = 0; i < Text.Length; i++) { if (!Char.IsNumber(Text, i)) { allNums = false; } } if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "en") { if (allNums) { if (Text.Length == 6) { Text = Text.Substring(0, 2) + "/" + Text.Substring(2, 2) + "/" + Text.Substring(4, 2); } else if (Text.Length == 8) { Text = Text.Substring(0, 2) + "/" + Text.Substring(2, 2) + "/" + Text.Substring(4, 4); } } } if (DateTime.Parse(Text).Year < 1870 || DateTime.Parse(Text).Year > 2070) { throw new Exception("Valid dates between 1870 and 2070"); } else { Text = DateTime.Parse(this.Text).ToString("d"); //will throw exception if invalid } errorProvider1.SetError(this, ""); } catch (Exception ex) { //Cancel the event and select the text to be corrected by the user if (ex.Message == "String was not recognized as a valid DateTime.") { myMessage = "Invalid date"; } else { myMessage = ex.Message; } //this.Select(0,this.Text.Length); errorProvider1.SetError(this, Lan.g("ValidDate", myMessage)); } }
private bool CheckControlHasText(Control control, string errorMessage) { if (control.Text.Trim().Length > 0) { errorProvider.SetError(control, ""); return(true); } errorProvider.SetError(control, errorMessage); return(false); }
private void ClearErrors() { foreach (Control textBox in this.Controls) { if (textBox is TextBox) { errorProvider.SetError(textBox, ""); } } }
private void Import_Click(object sender, EventArgs e) { bool OK = true; ErrorProvider errorProvider = new ErrorProvider(); if (string.IsNullOrWhiteSpace(Survey.Text)) { errorProvider.SetError(this.Survey, "必填。"); OK = false; } else errorProvider.SetError(this.Survey, ""); if (this.Template == null && string.IsNullOrWhiteSpace(FileName.Text)) { errorProvider.SetError(this.FileName, "請選擇樣版檔。"); OK = false; } else { errorProvider.SetError(this.FileName, ""); } if (!OK) return; try { string base64string = string.Empty; if (!string.IsNullOrEmpty(this.FileName.Text)) base64string = TransferFileToBase64String(this.FileName.Text); int SurveyID = int.Parse((this.Survey.Items[this.Survey.SelectedIndex] as ComboItem).Tag + ""); if (this.WriteTemplate(base64string, SurveyID)) { this.DialogResult = System.Windows.Forms.DialogResult.OK; MessageBox.Show("儲存成功。"); this.Close(); return; } else { this.DialogResult = System.Windows.Forms.DialogResult.None; return; } } catch (Exception ex) { MessageBox.Show(ex.Message); this.DialogResult = System.Windows.Forms.DialogResult.None; return; } }
public static bool ValidateRequiredField(ErrorProvider errorProvider, Control control) { if (string.IsNullOrEmpty(control.Text)) { errorProvider.SetError(control, "A mező kötelező"); return false; } errorProvider.SetError(control, null); return true; }
public static void ComboBoxValideNonVide(object sender, ErrorProvider errProvider, String errMessage, CancelEventArgs e) { var combobox = (ComboBox)sender; if (combobox.SelectedIndex < 0) { errProvider.SetError(combobox, errMessage); e.Cancel = true; } else { errProvider.SetError(combobox, ""); } }
private void validarDatos(ErrorProvider ep, TextBox txt) { if (txt.Text.Trim().Length == 0) { ep.Icon = Icon.FromHandle(((Bitmap)imageList1.Images[0]).GetHicon()); ep.SetError(txt, "Dato no válido"); } else { ep.Icon = Icon.FromHandle(((Bitmap)imageList1.Images[1]).GetHicon()); ep.SetError(txt, "Dato Correcto"); } }
/// <summary> /// Most forms use errorprovider for validation, this method is a utility method that will /// control the toggling of the errorprovider, and it returns a 1 if there was an error, /// and 0 if there wasn't. This is most often used with a int errorCount = 0; statement so /// the validation can determine if there were errors easily. /// </summary> /// <param name="test"></param> /// <param name="provider"></param> /// <param name="control"></param> /// <param name="msg"></param> /// <returns></returns> public static int ValidationHelper(bool test, ErrorProvider provider, Control control, string msg) { if (test) { provider.SetError(control, msg); return 1; } else { provider.SetError(control, ""); return 0; } }
public PeopleForm(string title=null, IPeopleFormDelegate peopleFormDelegate = null, bool openForUpdate = false,string surname="", string firstname="", string password="", string comment="") { if (null != title) this.Text = title; _openForUpdate = openForUpdate; _peopleFormDelegate = peopleFormDelegate; this.SetBounds(10, 10, 200, 220); Label lbl1, lbl2,lbl3, lbl4; TextBox txt1, txt2,txt3,txt4; Button btn = new Button(); this.Controls.Add(lbl1 = new Label()); lbl1.SetBounds(5, 5, 185, 18); lbl1.Text = "firstname"; this.Controls.Add(txt1 = new TextBox()); txt1.SetBounds(5, 25, 185, 18); txt1.Text = firstname; this.Controls.Add(lbl2 = new Label()); lbl2.Text = "surname"; lbl2.SetBounds(5, 45, 185, 18); this.Controls.Add(txt2 = new TextBox()); txt2.SetBounds(5, 65, 165, 18); txt2.Text = surname; this.Controls.Add(lbl3 = new Label()); lbl3.SetBounds(5, 85, 185, 18); lbl3.Text = "password"; this.Controls.Add(txt3 = new TextBox()); txt3.SetBounds(5, 105, 185, 18); txt3.Text = password; this.Controls.Add(lbl4 = new Label()); lbl4.SetBounds(5, 125, 185, 18); lbl4.Text = "comment"; this.Controls.Add(txt4 = new TextBox()); txt4.SetBounds(5, 145, 185, 18); txt4.Text = comment; this.Controls.Add(btn); btn.SetBounds(5, 165, 185, 18); ErrorProvider ep = new ErrorProvider(); ep.SetIconAlignment(txt2, ErrorIconAlignment.MiddleRight); ep.SetIconPadding(txt2, 2); btn.Text = openForUpdate ? "Save people" : "Add people"; btn.Click += (object sender1, EventArgs e1) => { if (string.IsNullOrWhiteSpace(txt2.Text)) { ep.SetError(txt2, "Surname must contain chars"); return; } ep.SetError(txt2, string.Empty); if (null != this._peopleFormDelegate) _peopleFormDelegate.saved(txt2.Text, txt1.Text, txt3.Text, txt4.Text); if(openForUpdate) this.Close(); }; }
public static bool ValidateConfirmField(ErrorProvider errorProvider, Control confirmField, Control referenceField) { if (!string.IsNullOrEmpty(confirmField.Text)) { if (referenceField.Text != confirmField.Text) { errorProvider.SetError(confirmField, "A két mező tartalma különbözik"); return false; } errorProvider.SetError(confirmField, null); } return true; }
private void LineName_ok_Click(object sender, EventArgs e) { ErrorProvider error = null; if (this.LineName.Text == "") { error = new ErrorProvider(); error.SetError(this.LineName, "Enter line name"); error_Label.Text = "Enter line name"; } SQLiteDataReader db_data_lines; SQLiteCommand db_cmd_lines = ProjectClass.db_con.CreateCommand(); ; db_cmd_lines.CommandText = "SELECT name FROM lines ;"; db_data_lines = db_cmd_lines.ExecuteReader(); while (db_data_lines.Read()) if (this.LineName.Text == db_data_lines.GetString(0)) { error = new ErrorProvider(); error.SetError(this.LineName, "line name exists"); error_Label.Text = "line name exists"; return; } { linename = this.LineName.Text; this.DialogResult = DialogResult.OK; } }
public static bool ValidateCheckList(CheckedListBox boxes, ErrorProvider errorProvider) { if(boxes.CheckedItems.Count > 0) return true; errorProvider.SetError(boxes, "Este campo es obligatorio"); return false; }
public static bool ValidateComboBox(ComboBox boxes, ErrorProvider errorProvider) { if (!boxes.SelectedIndex.Equals(-1)) return true; errorProvider.SetError(boxes, "Este campo es obligatorio"); return false; }
public bool formValido(ErrorProvider errorProvider) { bool validado = true; foreach (var objeto in objetosValidar) { switch (objeto.Tipo) { case TipoCampos.Texto: if (((TextBox)objeto.Objeto).Text == string.Empty) { errorProvider.SetError((Control)objeto.Objeto, objeto.Mensaje == string.Empty ? "Debe ingresar el valor solicidado" : objeto.Mensaje); validado = false; } break; case TipoCampos.Numero: break; default: break; } } return validado; }
public static void ContraseniasIguales(string PwdNueva, string PwdReNueva, object sender, ErrorProvider errorProvider, CancelEventArgs e) { if (PwdNueva != PwdReNueva) { errorProvider.SetError(((TextBox)sender), "Las Contraseñas no son Iguales"); } }
public static bool ContraseniaSegura(string Pwd, ErrorProvider error, object sender) { bool Estado = false; Regex Mayuscula = new Regex("[A-Z]"); Regex Minuscula = new Regex("[a-z]"); Regex Numeros = new Regex("[0-9]"); Regex Especial = new Regex("[^a-zA-Z0-9]"); if (Pwd.Length >= 6) { if (Mayuscula.Matches(Pwd).Count >= 1) { if (Minuscula.Matches(Pwd).Count >= 1) { if (Numeros.Matches(Pwd).Count >= 1) { if (Especial.Matches(Pwd).Count >= 1) { Estado = true; } } } } } if (!Estado) { error.SetError(((TextBox)sender), "La Contraseña es Insegura"); } return Estado; }
public static void TextBox_ValidatingNumeric(CancelEventArgs e, TextBox textBox, ErrorProvider errorProvider) { string errorMsg; if (ValueIsNumeric(textBox.Text, out errorMsg) && StringNotEmpty(textBox.Text, out errorMsg) && ValueNotNegative(textBox.Text, out errorMsg)) return; e.Cancel = true; errorProvider.SetError(textBox, errorMsg); }
public static void TextBox_ValidatingPort(CancelEventArgs e, TextBox textBox, ErrorProvider errorProvider) { string errorMsg; if (StringNotEmpty(textBox.Text, out errorMsg) && ValidPort(textBox.Text, out errorMsg)) return; e.Cancel = true; errorProvider.SetError(textBox, errorMsg); }
public static void NotNullCheck(Control checkControl, ErrorProvider errorProvider, CancelEventArgs e) { if (string.IsNullOrEmpty(checkControl.Text)) { e.Cancel = true; errorProvider.SetError(checkControl, "不能为空!"); } else { errorProvider.Clear(); } }
public static void RegexCheck(Control checkControl, ErrorProvider errorProvider, string regexStr, CancelEventArgs e) { if (!Regex.IsMatch(checkControl.Text, regexStr)) { e.Cancel = true; errorProvider.SetError(checkControl, "格式不正确!"); } else { errorProvider.Clear(); } }
public void GetandSetErrorTest () { Form myForm = new Form (); myForm.ShowInTaskbar = false; Label label1 = new Label (); Label label2 = new Label (); ErrorProvider myErrorProvider = new ErrorProvider (); Assert.AreEqual (string.Empty, myErrorProvider.GetError (label1), "#1"); myErrorProvider.SetError (label1, "ErrorMsg1"); Assert.AreEqual ("ErrorMsg1", myErrorProvider.GetError (label1), "#2"); Assert.AreEqual (string.Empty, myErrorProvider.GetError (label2), "#3"); myErrorProvider.SetError (label2, "ErrorMsg2"); Assert.AreEqual ("ErrorMsg2", myErrorProvider.GetError (label2), "#4"); myErrorProvider.SetError (label2, null); Assert.AreEqual ("ErrorMsg1", myErrorProvider.GetError (label1), "#5"); Assert.AreEqual (string.Empty, myErrorProvider.GetError (label2), "#6"); myForm.Dispose (); }
public static void NumerosConMensaje(TextBox para, ErrorProvider error) { switch (solo13Numeros(para)) { case 1: error.SetError(para, "Solo acepta valores numericos"); break; case 3: error.SetError(para, "No se aceptan caracteres especiales en este campo "); break; case 4: error.SetError(para, "Solo se aceptan 13 valores"); break; default: error.SetError(para, ""); break; } }
public static bool ValidateMontoPositivo(TextBox textBoxMonto, ErrorProvider errorProvider) { if(Convert.ToDecimal(textBoxMonto.Text) <= 0) { errorProvider.SetError(textBoxMonto, "El monto debe ser mayor a cero"); return false; } return true; }
public bool IsEmpty(Control control, string text, ErrorProvider errorProvider) { string errorMessage = ""; bool result = true; if (text == "") { errorMessage = "This is a required field"; errorProvider.SetError(control, errorMessage); } else { errorProvider.SetError(control, ""); result = false; } return result; }
private bool HasRequiredText(ErrorProvider provider, Control control, string name) { if (string.IsNullOrEmpty(control.Text)) { provider.SetError(control,string.Format("{0} is a required field",name)); return false; } return true; }
public static void VerificarNoVacios(object sender, CancelEventArgs e, ErrorProvider error) { if (sender is TextBox) { if (string.IsNullOrEmpty(((TextBox)sender).Text)) { error.SetError(((TextBox)sender), !string.IsNullOrEmpty(((TextBox)sender).Text) ? string.Empty : "Campo Obligatorio"); e.Cancel = true; } else { error.SetError(((TextBox)sender), ""); } return; } if (sender is NumericUpDown) { if (string.IsNullOrEmpty(((NumericUpDown)sender).Text)) { error.SetError(((NumericUpDown)sender), !string.IsNullOrEmpty(((NumericUpDown)sender).Text) ? string.Empty : "Campo Obligatorio"); e.Cancel = true; } else { error.Clear(); } return; } if (sender is ComboBox) { if (((ComboBox)sender).Items.Count <= 0) { error.SetError(((ComboBox)sender), (((ComboBox)sender).Items.Count > 0) ? string.Empty : "Campo Obligatorio"); e.Cancel = true; } else { error.Clear(); } return; } }
public static void TextBox_ValidatingCompression(CancelEventArgs e, TextBox textBox, ErrorProvider errorProvider) { string errorMsg; if (!StringNotEmpty(textBox.Text, out errorMsg) || !ValidCompression(textBox.Text, out errorMsg)) { e.Cancel = true; errorProvider.SetError(textBox, errorMsg); } }
private void okBtn_Click(object sender, EventArgs e) { if (nameTxt.Text == "") { ErrorProvider errorProvider = new ErrorProvider(); errorProvider.SetError(nameTxt, "You must enter a label for the grading period."); this.DialogResult = DialogResult.None; } }
private void openBtn_Click(object sender, EventArgs e) { if (gradingPeriodComboBox.SelectedIndex == 0) { ErrorProvider errorProvider = new ErrorProvider(); errorProvider.SetError(gradingPeriodComboBox, "You must select grading period."); this.DialogResult = DialogResult.None; } }
public static Control CreateDate(Indicator indicator, string val, ErrorProvider indicatorErrors, List<DynamicContainer> controlList) { var container = new DynamicContainer { Indicator = indicator }; var cntrl = new NullableDatePickerControl { Name = "dynamicDt" + indicator.Id.ToString(), Margin = new Padding(0, 5, 10, bottomPadding), ShowClear = !indicator.IsRequired, Value = DateTime.Now }; // Add the Control to the DynamicContainer for reference container.Control = cntrl; container.IsValid = () => { if (indicator.IsRequired && cntrl.GetValue() == DateTime.MinValue) { indicatorErrors.SetError(cntrl, Translations.Required); return false; } indicatorErrors.SetError(cntrl, ""); return true; }; cntrl.Validating += (s, e) => { container.IsValid(); }; DateTime dt = new DateTime(); if(DateTime.TryParseExact(val, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) cntrl.Value = dt; else cntrl.Value = DateTime.MinValue; container.GetValue = () => { if (cntrl.GetValue() == DateTime.MinValue) return ""; else return cntrl.GetValue().ToString("MM/dd/yyyy"); }; controlList.Add(container); return cntrl; }