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.
Related
I need to accept more than one value from the same textbox and store it into an arrya . I need something close to the below code :
string[] countries = new string[3];
private void accept_Click(object sender, EventArgs e)
{
countries[0] = textBox1.Text+" 1 ";
countries[1] = textBox1.Text + " 2 ";
countries[2] = textBox1.Text + " 3 ";
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);}
}
}
How do you split the different countries?
If you split it on each space you can do it like this:
string[] countries = textBox1.Text.Split(null);
If that is not a good solution maybe try and explain the expected output.
You can simply use a multiline textbox and split the input on newlines:
var countries = countriesTextBox.Text.Split(Environment.NewLine);
Why not just use a list? The following code will add the country's name entered in the textbox to the List<string> every time you click the accept button.
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
countries.Add(textBox1.Text);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
If you want to allow the user to enter multiple countries at once, the following will work if you put a comma in between each country name when entering them into the textbox:
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
var input = textBox1.Text.Split(',');
countries.AddRange(input);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
I have code like this:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string ext = Path.GetExtension(openFileDialog1.FileName);
if(string.Compare(ext, ".FDB") == 0)
{
string fileName = openFileDialog1.SafeFileName;
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
string databaseTxt = #"C:\Users\arist\AppData\Roaming\TDWork\";
string[] database = { fileDirectory + fileName };
if (Directory.Exists(databaseTxt))
{
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(databaseTxt);
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
}
else
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
e.Cancel = true;
}
}
Now, i want to create more buttons that open same file dialog. Problem is that i want to pass openFileDialog directory to different textboxes. So logic is this:
If i open with button1, pass value to textbox1,
If i open with button2, pass value to textbox2,
if i open with button3, pass value to textbox3.
So i wanted to create int check (1, 2, 3) so when i press button1, it pass check = 1 to OpenDialog1_FileOk, so i just do switch there and do actions.
Problem is i do not know how to pass it to handler, and if that is possible. Also if there is any other solution, please write it.
First, you could use your openfiledialog just like this, without handling a whole new function for it:
if(openFileDialog1.ShowDialog() == DialogResult.OK){
//...code
}
Second, for your goal you'll have to be sure that the names of your controls are exactly ending on the digit you want (e.g. "button1" and "textbox1"). Then you can do it like this:
void Button1Click(object sender, EventArgs e)
{
//MessageBox.Show(bt.Name[bt.Name.Length - 1].ToString());
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(!Path.GetExtension(openFileDialog1.FileName).EndsWith(".FDB")) //checking if the extension is .FDB (as you've shown in your example)
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
return; //return if it's not and no further code gets executed
}
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName); //getting the directory
string nameOfMyButton = (sender as Button).Name; //you get the name of your button
int lastDigitOfMyName = Convert.ToInt16(Name[Name.Length - 1]); //returns the number of your button
TextBox neededTextboxToShowDirectory = this.Controls.Find("textbox" + lastDigitOfMyName, true).FirstOrDefault() as TextBox; //this will search for a control with the name "textbox1"
neededTextboxToShowDirectory.Text = fileDirectory; //you display the text
//... doing the rest of your stuff here
}
}
You could use a private field where you save temporarily the text of your TextBox and deploy it in the click event like this:
private int whichButton = 0;
private void button1_Click(object sender, EventArgs e)
{
whichButton = 1;
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
whichButton = 2;
openFileDialog1.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
whichButton = 3;
openFileDialog1.ShowDialog();
}
use then the whichButton to choose
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
switch (whichButton)
{
....
}
}
I need to plot data from sensors of pH, Temperature and Humidity, the data is sent as a matrix from arduino to PC through the serial port.
I can show the data in a TextBox, but when I try to plot the data, it doesn't work (I don't know how to do it).
I just can plot the data when is not a matrix and it's data from just one sensor.
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 System.Threading.Tasks;
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;
namespace grafik1
{
public partial class Form1 : Form
{
private SerialPort sensport;
private DateTime datetime;
private string data;
private string data2;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = SerialPort.GetPortNames();
timer1.Start();
}
double rt = 0;
Boolean i = false;
private void timer1_Tick(object sender, EventArgs e)
{
rt = rt + 0.1;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
sensport.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox2.Text == "")
{
MessageBox.Show("Error");
}
else
{
sensport = new SerialPort();
sensport.BaudRate = int.Parse(comboBox2.Text);
sensport.PortName = comboBox1.Text;
sensport.Parity = Parity.None;
sensport.DataBits = 8;
sensport.StopBits = StopBits.One;
sensport.Handshake = Handshake.None;
sensport.DataReceived += sensport_DataReceived;
try
{
sensport.Open();
textBox1.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
void sensport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (i == false)
{
rt = 0;
i = true;
}
data = sensport.ReadLine();
this.chart1.Series["Data1"].Points.AddXY(rt, data);
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Day + "/" + datetime.Month + "/" + datetime.Year + "\t" + datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
txtData.AppendText(time + "\t" + data + "\n");
}
private void button2_Click(object sender, EventArgs e)
{
string directorio = textBox1.Text;
if (directorio == "")
{
MessageBox.Show("Error");
}
else {
try
{
string kayıtyeri = #"" + directorio + "";
this.chart1.SaveImage(("+kayityeri+"), ChartImageFormat.Png);
MessageBox.Show("Grafica guardada en " + kayıtyeri);
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
sensport.Close();
}
private void button4_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\MARIO GONZALEZ\Google Drive\VisualStudio\Arduino0_1\DATA";
string filename = "arduinoRTPv1.xls";
System.IO.File.WriteAllText(pathfile + filename, txtData.Text);
MessageBox.Show("Data saved");
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void chart1_Click(object sender, EventArgs e)
{
}
}
}
Let's assume you have prepared your chart, maybe like this:
chart1.Series.Clear();
chart1.Series.Add("ph");
chart1.Series.Add("Temp");
chart1.Series.Add("Hum");
chart1.Series["ph"].ChartType = SeriesChartType.Line;
chart1.Series["Temp"].ChartType = SeriesChartType.Line;
chart1.Series["Hum"].ChartType = SeriesChartType.Line;
chart1.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
chart1.ChartAreas[0].AxisY2.Title = "Temp";
chart1.ChartAreas[0].AxisY2.Maximum = 100;
Now you can add a string that contains some data blocks as shown in the comments..
string data = "7.5 23.8 67 \n8.5 23.1 72 \n7.0 25.8 66 \n";
..like this:
var dataBlocks = data.Split('\n');
foreach (var block in dataBlocks)
{
var numbers = block.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
// rt += someTime; (*)
for (int i = 0; i < numbers.Length; i++)
{
double n = double.NaN;
bool ok = double.TryParse(numbers[i], out n);
if (ok) chart1.Series[i].Points.AddXY(rt, n);
else
{
int p = chart1.Series[i].Points.AddXY(rt, 0);
chart1.Series[i].Points[p].IsEmpty = true;
Console.WriteLine("some error message..");
}
}
}
I have modified the data a little to show the changes a little better..
Note that I left out the counting up of your timer rt, which is why the chart shows the points with indexed x-values. For a real realtime plot do include it maybe here (*) !
If you keep adding data your chart will soon get rather crowded.
You will then either have to remove older data from the beginning or at least set a minimum and maximum x-values to restrict the display to a reasonably number of data points and or turn on zooming!
See here here and here for some examples and discussions of these things!
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;
}
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.