How to make String empty to converted textbox in c# - c#

Here is the form i made
When I enter an empty value in the textbox I meet exception unhandled page. I want to show an error messagebox when user enter an empty value to the textbox how can I do that ?
namespace Random_çalışması
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random rnd = new Random();
int number;
int answer;
private void button1_Click(object sender, EventArgs e)
{
number = rnd.Next(1, 101);
label1.Text = number.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
answer = Convert.ToInt32(textBox1.Text);
if(answer == number)
{
MessageBox.Show("Welcome to the page", "Welcome!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if(String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Icorrect entrance", "You can not acces to the page", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Icorrect entrance", "You can not acces to the page", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

Just add the empty test at the beginning of the method:
private void button2_Click(object sender, EventArgs e)
{
if ( textBox1.Text == "" )
{
MessageBox.Show(...);
return;
}
answer = Convert.ToInt32(textBox1.Text);
...
}
You can also use int.TryParse() instead of Convert to better catch conversion errors:.
How the int.TryParse actually works
You can also simply set the button disable by default instead and add this handler on the TextChanged event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
button.Enable = textBox1.Text != "";
}
And also do the int.TryParse here instead too:
private void textBox1_TextChanged(object sender, EventArgs e)
{
button.Enable = textBox1.Text != "" && int.TryParse(textBox1.Text, out _);
}
Hence the button is enabled only if not empty and convertible and you have a consistent UX.
Now the button click handler is:
private void button2_Click(object sender, EventArgs e)
{
answer = Convert.ToInt32(textBox1.Text);
if ( answer == number )
MessageBox.Show("Welcome to the page", "Welcome!", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Icorrect entrance", "You can not acces to the page", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Related

dataGridView default error dialog handle

I am trying to hide default datagridview error dialog.
I put in the code this event handler:
this.dataGridView2.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(dataGridView2_DataError);
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//empty so it doesn't show anything
}
But still when i try this and leave datagridview cell empty ( delete everything from it), it show me dialog box with error.
Screenshot of error:
Try to Handle and Cancel the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Also, subscribe to the event in InitializeComponent()
private void InitializeComponent()
{
//...
this.dataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView2_DataError);
}
try to use this code to handle the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Try the next code , it's work!
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
try
{
//To handle 'ConstraintException' default error dialog (for example, unique value)
if ((e.Exception) is System.Data.ConstraintException)
{
// ErrorText glyphs show
dataGridView1.Rows[e.RowIndex].ErrorText = "must be unique value";
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "must be unique value";
//...or MessageBox show
MessageBox.Show(e.Exception.Message, "Error ConstraintException",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
//Suppress a ConstraintException
e.ThrowException = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR: dataGridView1_DataError",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Retain the message in the textbox when the checkbox is still checked

I have 3 checkboxes with corresponding message in a textbox. My teacher wants the message to remain in the textbox when the checkbox is still checked and hide the text when it is unchecked. In my case when I checked the 3 checkboxes their 3 corresponding messages will appear but when I unchecked one of the checkboxes and the other two are still checked, all the message will disappear. My problem is when I unchecked one of the checkbox and and the other 2 are still checked the corresponding messages with the remaining two checked checkboxes will remain in their textboxes.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
if (chkCarWheels.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
if (chkCarAcceleration.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
if (chkCarBreakpad.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
Looks like you need to create message depending on checkboxes states. You can create method, which will do the job and call it when state of some checkbox changed.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
Or the better one - create one event handler for all checkboxes:
// use for chkCarWheels, chkCarAcceleration, chkCarBreakpad
private void chkCar_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void BuildMessage()
{
lblMessage.Text = "My " + txtName.Text + " Car";
if (chkCarWheels.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
if (chkCarAcceleration.Checked)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
if (chkCarBreakpad.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
}
You don't need to compare boolean values with true/false. Use those values directly if (chkCarWheels.Checked). And keep in mind that in C# we use CamelCase names form methods. Also consider to use StringBuilder to build whole message and then assign it to label:
private void BuildMessage()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("My {0} Car", txtName.Text);
if (chkCarWheels.Checked)
sb.Append(mycar.hasWheels(4));
if (chkCarAcceleration.Checked)
sb.Append(mycar.Accelerate());
if (chkCarBreakpad.Checked)
sb.Append((mycar.hasBreak());
lblMessage.Text = sb.ToString();
}
Try this:
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
chkCar()
}
private void chkCar()
{
string msg="";
if (chkCarWheels.Checked)
msg=msg+mycar.hasWheels(4);
if(chkCarAcceleration.Checked)
msg=msg+mycar.Accelerate();
if(chkCarBreakpad.Checked)
msg=msg+mycar.hasBreak();
lblMessage.Text=msg;
}

How can you use the enter key to transfer data from a textbox to a label

I have a quick and simple question on a small project that I'm starting out on my own in C# for a Windows form program with Visual Studio 2010. I can't seem to find the correct code to transfer the input data that a user enters into a textbox with a method where they hit the enter key and it automatically enters a message in that label on the same form.
Such as in the following code (which has been edited as suggestions are provided):
namespace MovieFinders2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
//Named "Enter a Year"
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
label2.Text = textBox1.Text;
label2.Text = "Movies released before " + textBox1.Text;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
label2.Text = textBox1.Text;
label2.Text = "Movies released before " + textBox1.Text;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
label3.Text = textBox1.Text;
label3.Text = "Movies released in or after " + textBox1.Text;
}
}
}
private void label3_Click(object sender, EventArgs e)
{
label3.Text = textBox1.Text;
label3.Text = "Movies released in or after " + textBox1.Text;
}
}
}
I know that this program is in the early stages, but I"m trying to take this one step at a time and this is the road block that I have encoutered at this point; so any and all help would be greatly appreciated. Right now when I click the mouse on the lable it displays the message in that label. I need this to appear in the label when the user presses the enter key.
Try this:
void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
label2.Text = textBox1.Text;
label2.Text = "Movies released before " + textBox1.Text;
}
}
TextBox.KeyDown event

How to check in real time if data was enteder from one of the classes into a texbox?

My question comes from a problem which I have right now. I have MainWindow, AuthenticateWindow, and AddEntryWindow which all are WinForms. In main window I have possibility to Authenticate and Add Entry into my main windows textbox. They can not add an entry until they authenticate (no problem with this). I need to add an entry to the text box which will update my main windows textbox. The problem if, how can I check if entry was added to my textbox?
I am trying to have a Save option from menu strip. I am getting an error whenever I am trying to save an empty file. How could I authenticate the saving process by Save button by having it first disabled, and enabled after entry was added?
I could always verify if if textbox had an entry but I want to have button disabled first, and enabled after entry was added. I do not have a privilege to do so as of right now.
Please ask questions if I am not clear enough.
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
if (txtDisplay.Text != string.Empty)
{
sfdSaveToLocation.ShowDialog();
}
}
MainWindow.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace Store_Passwords_and_Serial_Codes
{
public partial class MainWindow : Form
{
private AuthenticateUser storedAuth;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Load(object sender, EventArgs e)
{
// Prohibit editing.
txtDisplay.Enabled = false;
}
public string ChangeTextBox
{
get
{
return this.txtDisplay.Text;
}
set
{
this.txtDisplay.Text = value;
}
}
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
}
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
private void tsmiClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
sfdSaveToLocation.ShowDialog();
}
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string theFileName = sfdSaveToLocation.FileName;
EncryptDecrypt en = new EncryptDecrypt();
string encrypted = en.Encrypt(txtDisplay.Text,
storedAuth.UserName, storedAuth.Password);
MessageBox.Show(encrypted);
File.WriteAllText(theFileName, encrypted);
}
}
}
AddEntryWindow.cs
using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AddEntryWindow : Form
{
string user, pass;
// Initializind ArrayList to store all data needed to be added or retrived.
private ArrayList addedEntry = new ArrayList();
// Initializing MainWindow form.
MainWindow mainWindow;
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
public AddEntryWindow(MainWindow viaParameter, string user, string pass)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
}
private void AddEntryWindow_Load(object sender, EventArgs e)
{ }
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex == -1)
{
MessageBox.Show("Please select entry type!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Each field must be filled for specified type.
// Here we are checking if all fields were filled.
else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
{
MessageBox.Show("Please fill all the fields!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int totalEntries = 0;
if(cmbType.SelectedIndex == 0)
addedEntry.Add(new AddPC(cmbType.Text,
txtUserName.Text, txtPassword.Text));
else if(cmbType.SelectedIndex == 1)
addedEntry.Add(new AddWebSite(cmbType.Text,
txtUserName.Text, txtPassword.Text, txtURL.Text));
else if(cmbType.SelectedIndex == 2)
addedEntry.Add(new AddSerialCode(cmbType.Text,
txtSoftwareName.Text, txtSerialCode.Text));
StringBuilder stringBuilder = new StringBuilder();
foreach (var list in addedEntry)
{
if (list is AddPC)
{
totalEntries++;
AddPC tmp = (AddPC)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddWebSite)
{
totalEntries++;
AddWebSite tmp = (AddWebSite)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddSerialCode)
{
totalEntries++;
AddSerialCode tmp = (AddSerialCode)list;
stringBuilder.Append(tmp.ToString());
}
}
mainWindow.ChangeTextBox = stringBuilder.ToString();
mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";
// Clearing all fields.
ClearFields();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearFields();
}
private void btnClose_Click(object sender, EventArgs e)
{
// Closing the Add Entry Window form.
this.Close();
}
private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
{
// Deciding which data must be entered depending on
// what type is selected from combo box.
// PC
if (cmbType.SelectedIndex == 0)
{}
// Web Site
else if (cmbType.SelectedIndex == 1)
{}
// Serial Code
else if (cmbType.SelectedIndex == 2)
{}
}
private void ClearFields()
{
// Clearing all fields to the default state.
}
}
}
Regards.
It sounds like you probably just want to subscribe to the TextChanged event, which will be fired whenever the text in the textbox changes.
I can't say I really followed everything that you're doing, but I think you should be fine to just enable or disable your Save button within that event handler.
EDIT: It's not really clear where all your different components live, but you want something like:
// Put this after the InitializeComponent() call in the constructor.
txtDisplay.TextChanged += HandleTextBoxTextChanged;
...
private void HandleTextBoxTextChanged(object sender, EventArgs e)
{
bool gotText = txtDisplay.Text.Length > 0;
menuSaveButton.Enabled = gotText;
}
I'd also strongly advise you not to use ArrayList but to use the generic List<T> type. The non-generic collections should almost never be used in new code.

IndexOutOfRange Exception from String.Format

I want to search a file by the month of birth and display the results in label7. So what I want is to enter the number 11 into textbox5 press button4 and display all the enteries with a birthmonth of 11 into label7.text. The filename.txt is created in the first part of the program I now what to be able to search that filename.txt. Another example of what i am trying to do is. When the file was created data was entered Firstname, lastname, birthday, and birth month. I want to search that file by birth month and display the results in label7.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void tabPage2_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void close_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
writetext();
reset();
}
public void writetext()
{
using (TextWriter writer = File.AppendText("filename.txt"))
{
writer.WriteLine("First name, {0} Lastname, {1} Phone,{2} Day of birth,{3} Month of Birth{4}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text, textBox3.Text);
MessageBox.Show(String.Format("First Name,{0} Lastname, {1} Phone,{2} Day of birth,{3} Month of Birth{4}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text, textBox3.Text));
}
}
public void reset()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
maskedTextBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
private void button2_Click(object sender, EventArgs e)
{
readfile();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
string[] lines = ...
try
{
int month = Int32.parse(textBox5.Text);
label7.Text = String.Format("Month of Birth {0}", lines[month]);
}
catch(Exception e){
label7.Text = "Invalid input";
}
}
public void readfile()
{
string[] lines = File.ReadAllLines("filename.txt");
label6.Text = String.Join(Environment.NewLine, lines);
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
}
}
Instead
label7.Text = (String.Format("Month of Birth{4}", textBox5.Text));
Use
label7.Text = (String.Format("Month of Birth{0}", textBox5.Text));
The {0} 0 in curly brace means the 0-positioned argument in String.Format argument list, in this case, refers to textBox5.Text
--Update--
Seems you need to print the [month]-th line of the text file to Label7, the code should be:
string[] lines = ...
try{
int month = Int32.parse(textBox5.Text);
label7.Text = String.Format("Month of Birth {0}", lines[month]);
}
catch(Exception e){
label7.Text = "Invalid input";
}
Judging by your comment on xandy's answer, it is impossible for us to help you without knowing the file format of filename.txt. However, you probably want something like this.
private void button4_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines("filename.txt");
string result = GetResultFromLines(lines, textBox5.Text);
label7.Text = (String.Format("Month of Birth{0}", result));
}
You will have to write the GetResultFromLines function yourself, based on how you want to retrieve your data from file.
The number in brackets is not the field width - it's the index of the parameter to use.

Categories