I have a Currency Textbox with a mask.
Mask is shown in textbox as --------.--
So user types in digits over the mask.
Now customer says he does not want to type in letter from left to right.
He wants to type from right to left.
Similar to what we have in calculator.
Now I tried changing the textbox's righttoleft property but that does not help my cause.
In the end I am stuck with handling the key event to manually change the position.
I am able to change the position but getting stuck completing the logic.
Here's how my code looks like :
void Textbx_KeyDown(object sender, KeyEventArgs e)
{
String temp = T.Text;
string temp2 = T.Text;
int CursorIndex = T.SelectionStart - 1;
for (int i = 0; i <= CursorIndex; i++)
{
if (i == 7)
{
temp2 = temp2.Insert(i, temp[i + 2].ToString());
temp2 = temp2.Remove(i, 2);
//i = i + 2;
}
else if (CursorIndex == i)
{
temp2 = temp2.Remove(i, 1);
temp2 = temp2.Insert(i, temp[i + 1].ToString());
}
else
{
// T.Text = T.Text.Insert(i + 1, "_");
temp2 = temp2.Insert(i, temp[i + 1].ToString());
temp2 = temp2.Remove(i + 1, 1);
}
}
T.Text = temp2;
// T.Text = T.Text.Insert(CursorIndex-1, temp[CursorIndex].ToString());
if (CursorIndex != -1)
T.SelectionStart = CursorIndex - 1;
}
Is there a better way to do this? If not how should I go about completing the logic?
There is a property for that in the textbox:
T.RightToLeft = RightToLeft.Yes
I have written this code for you; please try it:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string mychar = "000000";
string mtxt;
int mypos = 6;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Text = mychar;
}
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
mtxt = mtxt + e.KeyChar;
mypos--;
mychar = mychar.Remove(mypos, mtxt.Length);
mychar = mychar.Insert(mypos, mtxt);
maskedTextBox1.Text = mychar;
}
}
}
try this using a maskedTextBox.
set TextMaskFormat Property = IncludePrompt
private void maskedTextBox1_Click(object sender, EventArgs e)
{
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char) Keys.Back)
{
String a = maskedTextBox1.Text + e.KeyChar;
maskedTextBox1.Text = a.Substring(1, a.Length - 1);
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
}
private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
maskedTextBox1.Text = "_" + maskedTextBox1.Text;
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
}
Related
I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
Here is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown
This is a simple calculator program I am trying to make using Windows Forms Application in VS. The UnhandledException appears when I click anywhere except on the calculator buttons. I am fairly new to C# and it seems that a sender button in my function "common_operators" is causing the exception. Also, I want this calculator to have similar memory functionalities as windows 10's built-in calculator. I've searched everywhere but couldn't find a c# calculator implementation that is similar to Win10's built-in calculator has, I have already started but I think there's a better way to implement it. If u need more info, I've uploaded the "designer.cs" file that relates to the form application.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp_Calculator;
namespace WindowsFormsApp_Calculator
{
public partial class CalculatorBase : Form
{
public double[] arrMemory = new double[5];
public int indexer = 0;
double result = 0;
string asmd_operator = ""; // ASMD - Addition, Subtraction, Multiplication, Division
bool insert_value = false;
public CalculatorBase()
{
InitializeComponent();
btn_mc.Enabled = false;
btn_mr.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void numbers_zerotonine(object sender, EventArgs e)
{
Button b = (Button)sender;
if((box_display.Text == "0") || insert_value)
box_display.Text = "";
insert_value = false;
box_display.Text = box_display.Text + b.Text;
}
private void common_operators(object sender, EventArgs e)
{
Button b = (Button)sender;
if (result != 0)
{
btn_eql.PerformClick();
insert_value = true;
asmd_operator = b.Text;
subbox_display.Text = result + " " + asmd_operator;
}
else
{
asmd_operator = b.Text;
result = double.Parse(box_display.Text);
box_display.Text = "";
subbox_display.Text = System.Convert.ToString(result) + " " + asmd_operator;
}
}
private void btn_ce_Click(object sender, EventArgs e)
{
box_display.Text = "0";
}
private void btn_c_Click(object sender, EventArgs e)
{
box_display.Text = "0";
subbox_display.Text = "";
result = 0;
}
private void btn_eql_Click(object sender, EventArgs e)
{
subbox_display.Text = "";
switch(asmd_operator)
{
case "-":
box_display.Text = (result - double.Parse(box_display.Text)).ToString();
break;
case "+":
box_display.Text = (result + double.Parse(box_display.Text)).ToString();
break;
case "X":
box_display.Text = (result * double.Parse(box_display.Text)).ToString();
break;
case "/":
box_display.Text = (result / double.Parse(box_display.Text)).ToString();
break;
default:
break;
}
result = double.Parse(box_display.Text);
asmd_operator = "";
}
private void btn_bs_Click(object sender, EventArgs e)
{
if(box_display.Text.Length > 0)
{
box_display.Text = box_display.Text.Remove(box_display.Text.Length - 1, 1);
}
if(box_display.Text == "")
{
box_display.Text = "0";
}
}
private void btn_ms_Click(object sender, EventArgs e)
{
if (indexer == 5)
{
mem_textbox.Text = "Memory is full. Max limit = 5";
}
else
{
int hgt = 75;
mem_textbox.Text = "";
arrMemory[indexer] = double.Parse(box_display.Text);
indexer++;
btn_mc.Enabled = true;
btn_mr.Enabled = true;
TextBox mem = new TextBox();
mem.Multiline = true;
mem.TextAlign = HorizontalAlignment.Right;
mem.Width = 275;
mem.Height = 70;
mem.Font = new Font(mem.Font.FontFamily, 20);
mem.Text = box_display.Text;
mem.Location = new Point(387, hgt);
this.Controls.Add(mem);
}
}
private void btn_mc_Click(object sender, EventArgs e)
{
foreach (int i in arrMemory)
{
arrMemory[i] = 0;
}
indexer = 0;
btn_mr.Enabled = false;
btn_mc.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void btn_mr_Click(object sender, EventArgs e)
{
box_display.Text = arrMemory[indexer].ToString();
}
private void btn_mp_Click(object sender, EventArgs e)
{
arrMemory[indexer] += double.Parse(box_display.Text);
}
private void btn_mm_Click(object sender, EventArgs e)
{
arrMemory[indexer] -= double.Parse(box_display.Text);
}
}
}
From your designer.cs you've got a Click event handler on the form itself that invokes common_operators, so if that gets fired, it will be an invalid cast since sender will be your CalculatorBase form type and not Button
I created, dynamically, a number of textBoxes. The user will write input in those textBoxes and then press a button ("SAVE").
I want to save the info from those textBoxes in an array(or string). Is it possible to implement something like this: for(i = 0; i < the_number_of_textBoxes; i++) MY_ARRAY_or_MY_STRING += textBox[i].Text; //I know this isn't correct
I'm sure there should be something similar to my "way of thinking", but I can't find it.
If I would always have the same number of texboxes, lets say 2, I could implement it like this: MY_ARRAY_or_MY_STRING = textBox1.Text + textBox2.Text;, but my textBoxes are dynamicaly generated.
Here is the code I use (although I don't think it will be of need), my program has 2 Forms (Form1 is noted as frm1) - It has nothing to do with my question, but maybe it helps, idk. If you need more info about what the program does, ask away, I wont write it here, because it may be useless info.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Add MySql Library
using MySql.Data.MySqlClient;
namespace Proiect
{
public partial class Form2 : Form
{
public Form1 frm1;
public int numar_textBox = 5;
public int numar_eticheta = 5;
public int numar_groupBox = 0;
public int LastTextBoxLeft = 15;
public int LastEtichetaLeft = 15;
public int LastGroupBoxLeft = 3;
public Form2()
{
InitializeComponent();
frm1 = new Form1();
}
private void Form2_Load(object sender, EventArgs e)
{
int i;
for (i = 0; i < frm1.get_nr_coloane(); i++)
AddNewGroupBox();
}
private void Form2_Click(object sender, EventArgs e)
{
Deselect.Focus(); //Deseleceaza orice element, mutand focusul pe un label fara text
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
/*
public int verifica_spatii(TextBox New_text_box)
{
int i, k=0;
if (New_text_box.Text == "") return 1;
else
{
for (i = 0; i < New_text_box.TextLength; i++)
if (New_text_box.Text[i] != ' ')
{
return 1;
}
return 0; // are numai spatii
}
}
*/
public void On_click()
{
}
public event EventHandler Click_event;
public System.Windows.Forms.GroupBox AddNewGroupBox()
{
EventHandler handler = Click_event;
System.Windows.Forms.GroupBox grp = new System.Windows.Forms.GroupBox();
this.Controls.Add(grp);
grp.Width = 133;
grp.Height = 50;
grp.Top = 10;
grp.Left = LastGroupBoxLeft;
LastGroupBoxLeft += grp.Width;
grp.Text = frm1.get_nume_coloane()[numar_groupBox];
numar_groupBox += 1;
TextBox txt = new TextBox();
txt.Top = 20;
txt.Left = 10;
numar_textBox = numar_textBox + 1;
grp.Controls.Add(txt);
txt.Leave += textBoxGeneral_LostFocus;
/////New_text_box.Click += handler(this,);
return grp;
}
private void textBoxGeneral_LostFocus(object sender, EventArgs e)
{
//ToolStripItem item = (ToolStripItem)sender;
// MessageBox.Show(item.Text);
}
private void button1_Click(object sender, EventArgs e)
{
string valorile_de_adaugat="";
int i;
for(i=0;i<numar_groupBox-1;i++)
valorile_de_adaugat+=textBox[i]
//MySqlCommand Salveaza_in_baza_de_date = new MySqlCommand("INSERT INTO " + frm1.get_nume_tabel_selectat() + " ("+ frm1.get_unirea_coloanelor + ") VALUES(22056, 15, 2000, 2004));
}
/*
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
*/
}
}
Thank you for your time,
Vlad
I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}
It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.
If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.
I have created a program for some class work and it all works fine, but I'm having some problems with the alignment of the multiple bits of info inserted into the list box on the same rows.
When I print it, it looks messy and also looks messy in the list box.
Is there anyway I can neaten it up a little? I've tried pad right with no joy and list views confuse the hell out of me. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using System.Collections;
namespace Assignment2
{
public partial class frmCalculator : Form
{
bool blnDot = false;
double dbAllPoints = 0;
double dbAllMoney = 0;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
ddbItems.Items.Add("Glass");
ddbItems.Items.Add("Paper");
ddbItems.Items.Add("Beverage Cans");
ddbItems.Items.Add("Tins");
ddbItems.Items.Add("Milk Cartons");
ddbItems.Items.Add("Juice Boxes");
ddbItems.Items.Add("Plastics");
ddbItems.Items.Add("Clothes");
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '.'))
{
MessageBox.Show("Please input a number!", "Error");
e.Handled = true;
}
if (e.KeyChar == '.')
{
if (blnDot == true) { e.Handled = true; }
else { blnDot = true; }
}
}
private void txtInput_MouseClick(object sender, MouseEventArgs e)
{
txtInput.Text = "";
}
private void btnCalculate_Click(object sender, EventArgs e)
{
String strItem = "";
double dbMoney = 0;
double dbPoints = 0;
int intPoint = 0;
double dbWeight = 0;
if (((txtInput.Text == "")||(txtInput.Text=="Input the weight")|| (ddbItems.SelectedIndex==0)))
{
MessageBox.Show("Please input a weight into the textbox and make a selection from the drop down box", "Error");
}
else
{
if (ddbItems.SelectedIndex == 1)
{
intPoint = 7;
strItem = ddbItems.Items[1].ToString();
}
if (ddbItems.SelectedIndex == 2)
{
intPoint = 8;
strItem = ddbItems.Items[2].ToString();
}
if (ddbItems.SelectedIndex == 3)
{
intPoint = 10;
strItem = ddbItems.Items[3].ToString();
}
if (ddbItems.SelectedIndex == 4)
{
intPoint = 10;
strItem = ddbItems.Items[4].ToString();
}
if (ddbItems.SelectedIndex == 5)
{
intPoint = 3;
strItem = ddbItems.Items[5].ToString();
}
if (ddbItems.SelectedIndex == 6)
{
intPoint = 3;
strItem = ddbItems.Items[6].ToString();
}
if (ddbItems.SelectedIndex == 7)
{
intPoint = 5;
strItem = ddbItems.Items[7].ToString();
}
if (ddbItems.SelectedIndex == 8)
{
intPoint = 6;
strItem = ddbItems.Items[8].ToString();
}
dbWeight = Convert.ToDouble(txtInput.Text);
dbPoints = intPoint * dbWeight;
dbMoney = dbPoints * 0.01;
dbAllPoints = dbAllPoints + dbPoints;
dbAllMoney = dbAllMoney + dbMoney;
lblTotals.Visible = true;
lblTotals.Text = "You have " + dbAllPoints.ToString() + " points, and you have earned £" + dbAllMoney.ToString("0.00");
lstResults.Items.Add(strItem + " " + dbWeight.ToString() + "kg " + dbPoints.ToString() + " points £" + dbMoney.ToString("0.00"));
txtInput.Text = "Input the weight";
ddbItems.SelectedIndex = 0;
blnDot = false;
}
}
private void btnEnd_Click(object sender, EventArgs e)
{
frmWelcome frmWelcome = (frmWelcome)Application.OpenForms["frmWelcome"];
frmWelcome.Close();
this.Dispose();
}
private void btnReset_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Are you sure you want to reset everything?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.No) return;
txtInput.Text = "Input the weight";
lstResults.Items.Clear();
ddbItems.SelectedIndex = 0;
lblTotals.Text = "";
lblTotals.Visible = false;
blnDot = false;
}
private void btnPrint_Click(object sender, EventArgs e)
{
int intMax;
intMax = lstResults.Items.Count;
String[] arrResults = new String[intMax];
int intLoop;
for (intLoop = 0; intLoop < intMax; intLoop++)
{
arrResults[intLoop] = lstResults.Items[intLoop].ToString();
}
Array.Sort(arrResults);
lstResults.Items.Clear();
for (intLoop = 0; intLoop < intMax; intLoop++)
{
lstResults.Items.Add(arrResults[intLoop]);
}
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String strLine = "";
int intLoop;
Font pfont = new Font("Verdana", 18, GraphicsUnit.Point);
int intLine = 75;
strLine = "Item Weight Points Money";
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
intLine = intLine + 30;
for (intLoop = 0; intLoop < lstResults.Items.Count; intLoop++)
{
strLine = strLine +lstResults.Items[intLoop];
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
intLine = intLine + 30;
strLine = "";
}
intLine = intLine + 30;
strLine = lblTotals.Text;
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
}
}
}
You should use a DataGridView control instead of a ListBox since you are trying to display "column" information.
Likewise, when printing, you should be doing the DrawString for each column as well so that they line up properly.
If you want to continue with what you are doing, then you should use a mono-spaced font like Courier, not Verdana, and count the spaces between then lengths of the words.