IndexOutOfRange Exception from String.Format - c#

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.

Related

How to make String empty to converted textbox in 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);
}

Why does this code generate a CS1525 ("invalid expression") compiler error?

I'm trying to make a program that, when a button is pressed, takes the words typed in the text box and adds it to a text file. This is what I have so far:
private void textBox1_TextChanged(object sender, EventArgs e)
{
File.WriteAllText(path, string());
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
File.WriteAllText(path, string());
}
The String keeps coming up with error code CS1525 ("invalid expression"). What am I doing wrong?
You will want to use the string from the TextBox.Text property
for example
File.WriteAllText(path, textBox1.Text);
or
File.WriteAllText(path, (sender as TextBox).Text);
And it sounds like you want to create a Button and assign a Click event and use that to save the Text from the TextBox to the file, and for that AppendAllText may be a better option.
private void button1_Click(object sender, EventArgs e)
{
File.AppendAllText(path, textBox1.Text);
}
Try this:-
using (StreamWriter sw1 = new StreamWriter("abc.txt"))
{
sw1.WriteLine(textBox1.Text);
}
or
private void textBox1_TextChanged(object sender, EventArgs e)
{
File.WriteAllText(path,textBox1.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
File.WriteAllText(path,textBox2.Text);
}

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

Search a file that was created

When I create the file and append to it the rest of the information I now want to have the ability to read the text file then display the Month of a birthday thats listed in the file.
I want to be able to pull in just the info by birthday. So if I choose month 11 I want to pull in all the data entries that have a birthmonth of 11 by pushing button4.
This is what I have so far;
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)
{
}
public void readfile()
{
string[] lines = File.ReadAllLines("filename.txt");
label6.Text = String.Join(Environment.NewLine, lines);
}
}
}
Same as Geoffrey but with C# and linq syntax:
You can filter the content of your file using the birth date and store it in a new array this way:
string[] persons = File.ReadAllLines(Server.MapPath("filename.txt"));
IEnumerable<string> personsWithBirthday =
from p in persons
where p.Contains("1980-08-21")
select p;
foreach (var person in personsWithBirthday)
Response.Write(person);
I would recommend you to define a standard date format in order to easily grab all the persons matching the search criteria.
Please forgive me for using vb.net syntax here as I am more acustomed to it. The translation should be quite straightforward though:
Dim rdr As New IO.StreamReader("filename.txt")
While rdr.Peek <> -1
Dim strLine as String = rdr.ReadLine()
If strLine.Contains("Birth Month,11") Then
Label6.Text &= strLine
End If
End While
rdr.Close()
Hope that helps.

Categories