i am trying to auto validate my c# application - c#

so far the application is working but i dont know how to auto validate, the user enters a number in a text box and the text box should never be empty when the user clicks button parse, any alternative suggestions as to how i can validate the application would be greatly appreciated
public Parse_Strings()
{
InitializeComponent();
this.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
}
private void Parse_Strings_Load(object sender, EventArgs e)
{
}
private void btn_exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_parse_Click(object sender, EventArgs e)
{
string[] temp = txtenter.Text.Split(",".ToCharArray());
{
if (temp.Length == 3)
{
txtname.Text = temp[0];
txtaccount.Text = temp[1];
txtpassword.Text = temp[2];
}
else if (temp.Length > 0)
{
MessageBox.Show(" cannot be empty ");
}
else if (temp.Length >= 3)
{
MessageBox.Show(" entry is above required range ");
}
}
}

Why don't you make your validation in Button Parse click event ? Like this:
if(!string.IsNullOrEmpty(this.txtenter.Text) &&
!(txtenter.Text.Replace(',' ,'').Any(x => char.IsLetter(x)))
{
string[] temp = txtenter.Text.Split(',');
...
}

Related

C# - txtbox.Undo() not working as expected for Del key

I'm making a Notepad variant in Visual Studio (Winform, C#). It has a toolstrip, with options such as Undo, Cut, Copy, Paste, Delete, etc. The shortcut keys are enabled and connected with the menu options (CTRL + Z, CTRL + C, etc).
The rest of the Notepad variant is filled with a multiline textbox.
The problem arises when I want to delete the text from the textbox via the Delete key, or the menu option - while that works (i.e. the characters to the right of the current caret position are deleted, selected characters are deleted, etc), I am unable to undo that specific action.
This is the relevant part of my code:
private void mnuCut_Click(object sender, EventArgs e)
{
if(txtbox.SelectedText != "")
{
txtbox.Cut();
}
}
private void mnuCopy_Click(object sender, EventArgs e)
{
if (txtbox.SelectedText != "")
{
txtbox.Copy();
}
}
private void mnuPaste_Click(object sender, EventArgs e)
{
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
if(txtbox.SelectionLength > 0)
{
txtbox.SelectionStart = txtbox.SelectionStart + txtbox.SelectionLength;
}
txtbox.Paste();
}
}
private void mnuUndo_Click(object sender, EventArgs e)
{
if(txtbox.CanUndo == true)
{
txtbox.Undo();
txtbox.ClearUndo();
}
}
private void txtbox_KeyUp(object sender, KeyEventArgs e)
{
// Delete
if(e.KeyCode == Keys.Delete)
{
if(txtbox.SelectionLength < 1)
{
txtbox.SelectionLength = 1;
}
txtbox.SelectedText = "";
}
// Select all
if(e.Modifiers == Keys.ControlKey && e.KeyCode == Keys.A)
{
txtbox.SelectAll();
}
}
private void mnuDelete_Click(object sender, EventArgs e)
{
if (txtbox.SelectionLength < 1)
{
txtbox.SelectionLength = 1;
}
txtbox.SelectedText = "";
}
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
txtbox.SelectAll();
}
I think the problem may be in the way I'm deleting characters with the mnuDelete_Click and KeyUp event handlers. The same thing happens if I replace txtbox.SelectedText = "" with txtbox.SelectedText = String.Empty.
I know that I might be better off by using, say, txtbox.Cut(), like this:
private void txtbox_KeyUp(object sender, KeyEventArgs e)
{
// Delete
if(e.KeyCode == Keys.Delete)
{
if(txtbox.SelectionLength < 1)
{
txtbox.SelectionLength = 1;
}
//txtbox.SelectedText = "";
txtbox.Cut();
}
// Select all
if(e.Modifiers == Keys.ControlKey && e.KeyCode == Keys.A)
{
txtbox.SelectAll();
}
}
private void mnuDelete_Click(object sender, EventArgs e)
{
if (txtbox.SelectionLength < 1)
{
txtbox.SelectionLength = 1;
}
//txtbox.SelectedText = "";
txtbox.Cut();
}
But, even though this works, it'll replace the current contents of the clipboard with whatever was deleted / cut, which is something I don't want.
Finally, I ended up using SendKeys.Send("{BACKSPACE}"), and that gave the desired functionality. But the solution doesn't feel right - the original action was pressing the Delete key, not the Backspace key.
So, my question is this - how can delete characters via the Delete key, and obtain the ability to undo it, without resorting to hacky solutions? Or does it make no difference in the end, because it works as it is?

How to make a button disabled when no text is in a textbox?

I need the buttons BtnCalculate and BtnMessageBox to be disabled when there is nothing in the TxtQuantity and TxtPrice Text boxes including when the program starts. Does anyone know how to do this? Obviously the "Quantity and price must not be empty" message will not be needed in the code anymore after changes are made. Thank you very much in advance! May be simple but IDK what I am doing.
Here is the CODE:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BtnCalculate_Click(object sender, EventArgs e)
{
//declare Variables
int intQuantity;
Decimal decPrice;
Decimal decTotal;
//make sure quantity and price are the same
// if string is null or empty retuern textbox
Decimal TAX_RATE = 0.06m;
if (OosTax.Checked == true)
{ TAX_RATE = 0.09m; }
if ((TxtQuantity.Text.Trim().Length == 0 || (TxtPrice.Text == "")))
{ MessageBox.Show("Quantity and price must not be empty", "Calculator", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); }
else
{
try
{
intQuantity = Int32.Parse(TxtQuantity.Text);
decPrice = Decimal.Parse(TxtPrice.Text);
decTotal = (intQuantity * decPrice) * (1 + TAX_RATE);
LblMessage.Text = decTotal.ToString("C");
}
catch (Exception ex)
{ // Send Focus to Quantity
TxtQuantity.Focus();
TxtQuantity.SelectAll();
}
}
}
private void BtnMessageBox_Click(object sender, EventArgs e)
{
//declare Variables
int intQuantity;
Decimal decPrice;
Decimal decTotal;
string message = "Your Total Is: ";
Decimal TAX_RATE = 0.06m;
if (OosTax.Checked == true)
{ TAX_RATE = 0.09m; }
//make sure quantity and price are the same
// if string is null or empty retuern textbox
if ((TxtQuantity.Text.Trim().Length == 0 || (TxtPrice.Text == "")))
{ MessageBox.Show("Quantity and price must not be empty", "Calculator", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); }
else
{
try
{
intQuantity = Int32.Parse(TxtQuantity.Text);
decPrice = Decimal.Parse(TxtPrice.Text);
decTotal = (intQuantity * decPrice) * (1 + TAX_RATE);
// Display Total Currency as
MessageBox.Show(message + System.Environment.NewLine + decTotal.ToString("C"), "Chapter Two",
MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
catch (Exception ex)
{ // Send Focus to Quantity
TxtQuantity.Focus();
TxtQuantity.SelectAll();
}
}
}
private void BtnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void BtnClear_Click(object sender, EventArgs e)
{
LblMessage.Text = String.Empty;
}
}
use TextChanged event on textbox
like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
button1.Enabled = (textBox1.Text.Length > 0);
}
if you wish to do this on window loaded,
use
textBox1_TextChanged(null,null);
on loaded event
I would just write a method that sets the button enabled property based on the textbox text length of the two textbox controls, and then call it from the form Load event and the TextChanged event of the textboxes:
private void Form1_Load(object sender, EventArgs e)
{
ButtonEnabler();
}
private void txtPrice_TextChanged(object sender, EventArgs e)
{
ButtonEnabler();
}
private void txtQuantity_TextChanged(object sender, EventArgs e)
{
ButtonEnabler();
}
private void ButtonEnabler()
{
bool enabled = txtPrice.TextLength > 0 && txtQuantity.TextLength > 0;
btnCalculate.Enabled = enabled;
btnMessageBox.Enabled = enabled;
}

Need help integrating the math class in a windows forms calculator

First of all I'm sorry for the bad title. I'm a beginner so I don't have the vocabulary to accurately express what I need help with within one sentence.
I am currently trying to program a calculator. The calculator looks like this:
All of the buttons in the left area are working perfectly, but I'm having trouble coding for the buttons on the right. The program works by simply taking the string in the display and calculating it, but that doesn't work with the buttons on the right. For example I want the display to show √x and calculate the answer by using Math.Sqrt(x) when the user presses the √-button, I don't want the display to show Math.Sqrt(x).
My code looks like this:
public partial class Calculator : Form
{
String mathOperator;
public Calculator()
{
InitializeComponent();
}
private void number_Click(object sender, EventArgs e)
{
if (tbxDisplay.Text == "0")
{
tbxDisplay.Clear();
}
Button btnNumber = (Button)sender;
tbxDisplay.Text = tbxDisplay.Text + btnNumber.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
tbxDisplay.Text = "0";
}
private void operator_Click(object sender, EventArgs e)
{
Button btnOperator = (Button)sender;
mathOperator = btnOperator.Text;
if ((btnOperator.Text == "(" ) && tbxDisplay.Text == "0")
{
tbxDisplay.Clear();
tbxDisplay.Text = tbxDisplay.Text + btnOperator.Text;
}
else
{
tbxDisplay.Text = tbxDisplay.Text + btnOperator.Text;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
var v = dt.Compute(tbxDisplay.Text, "");
string answer = v.ToString();
answer = answer.Replace(',', '.');
if (answer.Contains(".0"))
{
answer = answer.TrimEnd('0');
if (answer.EndsWith("."))
answer = answer.TrimEnd('.');
}
tbxDisplay.Text = answer;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (tbxDisplay.Text.Length > 0 && tbxSDisplay.Text.Length != 1)
{
tbxDisplay.Text =
tbxDisplay.Text.Remove(tbxDisplay.Text.Length - 1, 1);
}
if (tbxDisplay.Text.Length == 1)
{
tbxDisplay.Text = "0";
}
}
private void btnBack_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
private void btnPi_Click(object sender, EventArgs e)
{
tbxDisplay.Text = tbxDisplay.Text + "3.14159265359";
//this is my solution for now
//but as you can see it's very ugly
}
}

Textbox autocomplete - input from custom keyboard on screen

I'm trying to use autocomplete. The input text comes from a custom made keyboard, made from a form.
I tried autocomplete feature from a simple textbox and text input from my keyboard and works fine. But when I input text from the custom keyboard, it doesn't work. The custom keyboard adds the input from a key listener Key_Click.
I tried adding an extra 'a' and adding the text as txtInput.Text += 'o'; but it didn't work.
Any ideas?
keyboard code:
public partial class frmTextInput : Form
{
public string input_Text { get; set; }
public frmTextInput(string TEXT,bool CTRL)
{
InitializeComponent();
AlternarTeclas(chkShift.Checked);
AgregarListenerTeclas();
var source = new AutoCompleteStringCollection();
List<string> box = Data.Data.SourcePatente();
foreach (var item in box)
{
source.Add(item);
}
txtInput.AutoCompleteCustomSource = source;
txtInput.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
private void btnSpace_Click(object sender, EventArgs e)
{
txtInput.Text = txtInput.Text + " ";
}
private void btnBorrar_Click(object sender, EventArgs e)
{
string str = txtInput.Text;
if (!string.IsNullOrEmpty(str))
{
txtInput.Text = str.TrimEnd(str[str.Length - 1]);
}
}
private void btnVolver_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnEnter_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
input_Text = txtInput.Text;
}
private void frmTextInput_Load(object sender, EventArgs e)
{
}
private void chkShift_CheckedChanged(object sender, EventArgs e)
{
AlternarTeclas(chkShift.Checked);
}
private void Key_Click(object sender, EventArgs e)
{
string key = sender.ToString();
if (chkShift.Checked)
{
key = key.ToUpper();
}
else
{
key = key.ToLower();
}
txtInput.Text = txtInput.Text + key.Substring(key.Length - 1);
}
private void AgregarListenerTeclas()
{
foreach (Control c in tabCaracteres.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length == 1 && c.Text != "←")
{
c.Click += Key_Click;
}
}
}
foreach (Control c in tabSymbol.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length == 1 && c.Text != "←")
{
c.Click += Key_Click;
}
}
}
}
private void AlternarTeclas(bool estaShiftApretado)
{
if (estaShiftApretado)
{
foreach (Control c in tabCaracteres.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length < 2)
{
c.Text = c.Text.ToUpper();
}
}
}
}
else
{
foreach (Control c in tabCaracteres.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length < 2)
{
c.Text = c.Text.ToLower();
}
}
}
}
}
private void btnSymbol_Click(object sender, EventArgs e)
{
tabTeclado.SelectTab(tabTeclado.SelectedIndex + 1);
}
private void btnTecAlfanumerico_Click(object sender, EventArgs e)
{
tabTeclado.SelectTab(tabTeclado.SelectedIndex - 1);
}
private void button1_Click(object sender, EventArgs e)
{
txtInput.Text += 'o';
}
}
txtInput.AutoCompleteCustomSource = source;
txtInput.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
This should be put in the designer file of your textbox, not here. Try that, and can you see your textbox text value change when you use the custom keyboard? What I understand is you catch click event for your custom keyboard and change txtInput.Text?
I made it work. First of all, it didn't work with textbox multiline.
Then, the correct way to input new chars was emulate the keyboard:
I was triying in function "Key_Click":
== txtInput.Text = txtInput.Text + key.Substring(key.Length - 1); ==> I don't work
Instead I used:
== txtInput.Focus(); // IMPORTANT
SendKeys.Send(key.Substring(key.Length - 1));

second column of grid view accept only numbers in c# windows forms

I have a grid view..in my second column of grid view i want to enter only numerics
so i given code like this:
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 2)
{
int i;
if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
label1.Text ="please enter numeric";
}
else
{
}
}
}
but before doing this i want to check wethar this column contains any value or not? if any value contains then only i want to check wethar this value is numeric or not? how i can do this?
any help is very appreciable?
Simply check for a blank string first, so something like:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 1)
{
int i;
if (!string.IsNullOrEmpty(e.FormattedValue) && !int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
label1.Text ="please enter numeric";
}
else
{
}
}
}

Categories