I am coding a program where I need to read, write, and filter data from one text file to a new one.
The main goal of this program is:
have the user select a text file with data that I have already created,
use a Substring to choose which characters to grab from the file,
write a file that matches the data from the text file.
I am a little stuck on getting the program to write files in general as well as grabbing certain characters from a text file.
If anyone could give me some pointers that would be awesome.
Thanks!
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 System.Diagnostics;
using System.IO;
namespace Project_4_osmvoe
{
public partial class Form1 : Form
{
string ham;
StreamReader pizza;
StreamWriter burger;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ham = openFileDialog1.FileName;
}
pizza = new StreamReader(ham);
lblInputFile.Text = ham;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ham = saveFileDialog1.FileName;
}
burger = new StreamWriter(ham);
lblOutputFile.Text = ham;
}
private void button3_Click(object sender, EventArgs e)
{
string line;
while ((line = pizza.ReadLine()) != null)
{
if (filter(line))
burger.WriteLine(line);
}
pizza.Close();
burger.Close();
MessageBox.Show("Output File Written");
}
private Boolean filter(string intext)
{
string gender = intext.Substring(0, 0);
string state = intext.Substring(0, 0);
if (((radioButtonFemale.Checked && gender.Equals("F")) ||
(RadioButtonMale.Checked && gender.Equals("M"))))
return true;
else
return false;
}
}
}
A part from the useful advices received in the comments above.
(Don't keep streams opened between events)
What do you think is the result of these lines?
string gender = intext.Substring(0, 0);
string state = intext.Substring(0, 0);
THe second parameter of Substring is the number of chars to extract from the string. Passing zero means that your returned string is empty, so the subsequent test is always false and you never write a line.
I suggest to store, in two different global variables, the names of the two files and, in button3_Click open the two streams
string inputFile;
string outputFile;
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
inputFile = openFileDialog1.FileName;
lblInputFile.Text = inputFile;
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
outputFile = saveFileDialog1.FileName;
lblOutputFile.Text = outputFile ;
}
}
private void button3_Click(object sender, EventArgs e)
{
string line;
using(StreamReader pizza = new StreamReader(inputFile))
using(StreamWriter burger = new StreamWrite(outputFile))
{
while ((line = pizza.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line) && filter(line))
burger.WriteLine(line);
}
}
MessageBox.Show("Output File Written");
}
private Boolean filter(string intext)
{
string gender = intext.Substring(0, 1);
string state = intext.Substring(0, 1);
if (((radioButtonFemale.Checked && gender.Equals("F")) ||
(RadioButtonMale.Checked && gender.Equals("M"))))
return true;
else
return false;
}
Related
I'll try to add as much information as needed, please tell me if you need any extra info that I haven't added and I'll do my best to provide it.
The basics of my problem is that whenenver I press a button, it will grab the file I select and save it to a text file. This works fine and I can save as many files as needed. The problem lies in the listbox of my listbox. My app is a soundboard, and I want filenames with their hotkeys to be displayed on the listbox which almost works fine. On loading the application the listbox will take all saved files and display them accordingly once and on adding a file, the file will be added to the listbox and it will be saved. As I said this almost works because for some reason unknown to me, you have to click the listbox for it to add the content. My code is as follows:
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
songToAdd = filePath;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
add = true;
}
}
public bool add = false;
public string songToAdd;
public bool load = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == true)
{
listBox1.DataSource = File.ReadAllLines(#"Sounds.txt");
load = false;
}
if(add == true)
{
listBox1.Items.Add(songToAdd);
add = false;
}
}
}
P.S. I'm still a novice at windows forms and this app is still nowhere near done.
Instead of adding the items in SelectedIndexChanged I added them in outside. I load the saved songs in Form1_Load and I open/save the loaded files in the addFile() function.
Edited 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;
using System.IO;
using System.Media;
using System.Security.Cryptography.X509Certificates;
using System.Runtime;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Diagnostics;
namespace SoundBoard
{
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public bool load = true;
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
listBox1.Items.Add(filePath);
}
}
public bool loada = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (loada == true)
{
listBox1.Items.Add(File.ReadAllLines(#"Sounds.txt"));
loada = false;
}
}
}
}
I already got most of the help I needed in order to create a working button to save my scraped proxies to a .txt file, but I still run into one issue. This is the code that I have gotten so far, it works perfectly fine:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Windows.Forms;
using System.IO;
namespace CyberScraper
{
public partial class Base_Scraper : Form
{
WebClient _WC = new WebClient();
Defaults _DF = new Defaults();
public Base_Scraper()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
private void Base_Scraper_Load(object sender, EventArgs e)
{
MessageBox.Show("twitch.tv/CyberLost same YT Name");
}
private void ScrapeTheProxies()
{
try
{
foreach (string Source in ScrapeSources.Lines)
{
string UnparsedWebSource = _WC.DownloadString(Source);
MatchCollection _MC = _DF.REGEX.Matches(UnparsedWebSource);
foreach (Match Proxy in _MC)
{
GatheredProxies.Items.Add(Proxy);
}
}
}
catch (Exception)
{
}
}
private void SaveProxyResults_Click(object sender, System.EventArgs e)
{
Stream myStream;
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "";
dlg.InitialDirectory = #"C:\Users\username\Desktop";
dlg.Filter = "txt files (*.txt)|*.txt";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if ((myStream = dlg.OpenFile()) != null)
{
myStream.Close();
StreamWriter writer = new StreamWriter(dlg.FileName);
for (int i = 0; i < GatheredProxies.Items.Count; i++)
{
writer.WriteLine((string)GatheredProxies.Items[i]);
}
writer.Close();
}
}
dlg.Dispose();
}
private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
ScrapeTheProxies();
}
private void ScrapeButton_Click(object sender, EventArgs e)
{
BackgroundWorker.RunWorkerAsync();
}
}
}
When I click on "Save Results" it works before I scraped the proxies, if I do it after finishing scraping the proxies it outputs this error and saves it on the desktop as an empty .txt file instead of a .txt file containing the scraped proxies:
System.InvalidCastException: 'Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.String'.'
in:
writer.WriteLine((string)GatheredProxies.Items[i]);
So I am trying to copy a file from a source to a destination. I'm creating a windows form where i have buttons, source and destination. They are used to get a file and then get a desination. then another button is used to copy that file to the destination. when i click the destination, I get 'The directory name is invalid'.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CopyDirectory
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string file = "";
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//opens the file source & shows it in a label
file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
int size = text.Length;
string sfile = Path.GetFileName(file);
lbl_sfile.Text = sfile; // for full location
}
catch (IOException)
{
}
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//saves the file destination & shows it in a label
//use file2 string to save file into destination
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
lbl_dfile.Text = folderBrowserDialog1.SelectedPath;
}
}
}
private void Caluculate(int i)
{
double pow = Math.Pow(i, i);
}
private void bttn_savefile_Click(object sender, EventArgs e)
{
//collect label text as strings
string file2 = lbl_sfile.Text.ToString();
string file3 = lbl_dfile.Text.ToString();
string sourceDir = file;
string backupDir = folderBrowserDialog1.SelectedPath;
Path.Combine(file2, Path.GetFileName(file3));
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Set the initial value of the ProgressBar.
progressBar1.Value = 10;
progressBar1.Maximum = 100000;
progressBar1.Step = 1;
for (int j = 0; j < 100000; j++)
{
Caluculate(j);
progressBar1.PerformStep();
}
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}
First of all, for some clean code, your field named file should at least be a property and the name should reflect what it actually is, so:
string file = "";
to
private string FileFullPath { get; set; }
Then the real problem is that you are assigning the full path of the file, including its name to file: file = openFileDialog1.FileName; but then treating it as a directory string sourceDir = file; that should be obvious as to why that would fail... if not... you need to take the full path and just get the directory ie:
var sourceDir = Path.GetDirectoryName(FileFullPath);
am new to c#,Here am trying to read multiple txt files with its contents at once, then using textbox to collect all the txt content, after collecting the content then I will save all the content back into once txt file. below is my code, pls help out.
Here is the interface of the app
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 System.IO;
namespace FileSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
//File 004: Save the File in System Temporary path
private void button2_Click(object sender, EventArgs e)
{
if (txtFileContent.Visible == true)
{
SaveFile(Path.GetTempPath());
}
else
MessageBox.Show("This form saves only text files");
}
//File 001: Use File open dialog to get the file name
private void btn_File_Open_Click(object sender, EventArgs e)
{
List<String> MyStream = new List<string>();
string ext = "";
this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
this.dlgFileOpen.Multiselect = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
try
{
StringBuilder stbuilder = new StringBuilder();
foreach (var files in dlgFileOpen.SafeFileNames )
{
MyStream.Add(files + "\n");
Console.WriteLine();
}
foreach (var item in MyStream)
{
stbuilder.Append(item );
}
txtSelectedFile.Text = stbuilder.ToString() ;
ext = Path.GetExtension(dlgFileOpen.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
if (ext == ".txt")
{
//003: The extension is txt. Read the file and display the content
txtFileContent.Visible = true;
FileStream filestream = new FileStream(dlgFileOpen.FileName, FileMode.Open);
StreamReader streamReader = new StreamReader(filestream);
while (streamReader.EndOfStream != true)
{
txtFileContent.AppendText(streamReader.ReadLine());
txtFileContent.AppendText(Environment.NewLine);
}
streamReader.Close();
}
}
}
private void txtSelectedFile_TextChanged(object sender, EventArgs e)
{
}
//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
string Required_Ext = ".txt ";
string selected_ext = Path.GetExtension(dlgFileOpen.FileName);
int index = Required_Ext.IndexOf(selected_ext);
//002: Inform the user to select correct extension
if (index < 0)
{
MessageBox.Show("Extension Maaaan... Extension! Open only txt or bmp or jpg");
e.Cancel = true;
}
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void SaveFile_Click(object sender, EventArgs e)
{
//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
{
selected_path = dlgFolder.SelectedPath;
if (string.IsNullOrEmpty(selected_path) == true)
{
MessageBox.Show("Unable to save. No Folder Selected.");
return;
}
}
//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
{
SaveFile(selected_path);
}
else
MessageBox.Show("This form saves only text files");
}
public void SaveFile(string selected_path)
{
string Save_File;
if (selected_path.Length > 3)
Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
else
Save_File = selected_path + txtSaveFile.Text + ".txt";
FileStream fstream = new FileStream(Save_File, FileMode.CreateNew);
StreamWriter writer = new StreamWriter(fstream);
writer.Write(txtFileContent.Text);
lblSavedLocation.Text = "Text File Saved in " + Save_File;
writer.Close();
}
private void txtSaveFile_TextChanged(object sender, EventArgs e)
{
}
}
}
Try this out. I stripped out all the the code i felt unnecessary for your problem:
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 System.IO;
namespace FileSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
//File 004: Save the File in System Temporary path
private void button2_Click(object sender, EventArgs e)
{
if (txtFileContent.Visible == true)
{
SaveFile(Path.GetTempPath());
}
else
MessageBox.Show("This form saves only text files");
}
//File 001: Use File open dialog to get the file name
private void btn_File_Open_Click(object sender, EventArgs e)
{
this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
this.dlgFileOpen.Multiselect = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
var stBuilder = new StringBuilder();
foreach (var fileName in dlgFileOPen.FileNames)
{
stBuilder.AppendLine(File.ReadAllText(fileName));
}
txtFileContent.Text = stBuilder.ToString();
}
}
private void txtSelectedFile_TextChanged(object sender, EventArgs e)
{
}
//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void SaveFile_Click(object sender, EventArgs e)
{
//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
{
selected_path = dlgFolder.SelectedPath;
if (string.IsNullOrEmpty(selected_path) == true)
{
MessageBox.Show("Unable to save. No Folder Selected.");
return;
}
}
//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
{
SaveFile(selected_path);
}
else
MessageBox.Show("This form saves only text files");
}
public void SaveFile(string selected_path)
{
string Save_File;
if (selected_path.Length > 3)
Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
else
Save_File = selected_path + txtSaveFile.Text + ".txt";
File.WriteAllText(Save_File, txtFileContent.Text);
lblSavedLocation.Text = "Text File Saved in " + Save_File;
}
private void txtSaveFile_TextChanged(object sender, EventArgs e)
{
}
}
}
All looks good, except for the reading part, it can be done in a much easier way....
StringBuilder stbuilder = new StringBuilder();
foreach (var filePath in dlgFileOpen.FileNames)
{
StreamReader sr = new StreamReader(filePath);
stbuilder.Append(sr.ReadToEnd());
sr.Close();
//Or Much faster you can use
stbuilder.Append(File.ReadAllText(filePath));
stbuilder.Append(Environment.NewLine);
stbuilder.Append(Environment.NewLine);
txtFileContent.Text = stbuilder.ToString();
}
I've been trying to do this for a while now and just cannot get the code to execute the way I want it to. When running the program in C# visual studio, I click the submit button and instead of alerting me with errors because of the blank text boxes, it does nothing. I wanted to know how to execute the errorProvider or "errorCheck" in my code within the SUBMIT button (txtSubmit) so that it brings up the errors.
Here is the code I have so far:
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.IO; //input output external files (.text)
using System.Text.RegularExpressions; //handles errors
using System.Xml;
namespace H1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
//Exits the application when pressed
Application.Exit();
}
private void btnClear_Click(object sender, EventArgs e)
{
//clears the fields when clicked
txtPid.Text = ""; //Patient Information Fields
txtPname.Text = "";
txtPphone.Text = "";
txtPaddress.Text = "";
txtPemail.Text = "";
txtPhysician.Text = ""; //Last visit fields
txtDate.Text = "";
txtReason.Text = "";
txtIid.Text = ""; //Insurance information fields
txtIcompany.Text = "";
txtIphone.Text = "";
txtIinsured.Text = "";
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string[] dat = new string[12]; //Declare new string array, 12 because 0 is included in count
dat[0] = txtPid.Text; //Patient Information Fields
dat[1] = txtPname.Text;
dat[2] = txtPphone.Text;
dat[3] = txtPaddress.Text;
dat[4] = txtPemail.Text;
dat[5] = txtPhysician.Text; //Last visit fields
dat[6] = txtDate.Text;
dat[7] = txtReason.Text;
dat[8] = txtIid.Text; //Insurance information fields
dat[9] = txtIcompany.Text;
dat[10] = txtIphone.Text;
dat[11] = txtIinsured.Text; //Array is now fully populated
StreamWriter sw = new StreamWriter("PatientInfo.txt"); //Declare a new writer
for(int i = 0; i < dat.Length; i++) //Iterate through the array
{
sw.WriteLine(dat[i]); //Writes the current position in a new line to specified file
}
sw.Close(); //Close our writer, don't need unused junk left open
}
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("PatientInfo.txt"); //Specifies a new stream reader to read the file "File.dat"
String dat = sr.ReadToEnd(); //Reads the file until end and assigns it to the string "dat"
sr.Close(); //Close reader
dat = dat.Replace("\r", ""); //Removes all instances of carriage return, for handling/compatibility
string[] arr = dat.Split('\n'); //Splits the string into an array based on the new line character
}
private void txtPid_Validating(object sender, CancelEventArgs e)
{
// defines match
Match m = Regex.Match(txtPid.Text, #"\b[0-7]{7}\b"); //regular expressions
if (m.Success == false) //if does not match then provide below message
errorCheck.SetError(txtPid, "Patent I.D. must be 7 characters."); //error message
else errorCheck.SetError(txtPid, ""); //clears
}
private void txtPname_Validating(object sender, CancelEventArgs e)
{
if (txtPname.Text.Length < 3) //checks to see if there are less than 3 characters
{
errorCheck.SetError(txtPname, "Please enter the first and last name.");
}
else if (txtPname.Text.IndexOf(' ') == -1)
{
errorCheck.SetError(txtPname, "Must have both names seperated by a space.");
}
else errorCheck.SetError(txtPname, ""); //clears
}
private void txtPaddress_Validating(object sender, EventArgs e)
{
if (txtPaddress.Text == "")
{
errorCheck.SetError(txtPaddress, "You must enter the address.");
}
else errorCheck.SetError(txtPaddress, ""); //clears
}
private void txtPphone_Validating(object sender, CancelEventArgs e)
{
if (txtPphone.Text != "Valid")
{
errorCheck.SetError(txtPphone, "Telephone Number must be in proper format");
}
else errorCheck.SetError(txtPphone, "");
}
private void txtPemail_Validating(object sender, CancelEventArgs e)
{
if (txtPemail.Text == "") //checking for blanks
{
errorCheck.SetError(txtPemail, "You must enter an e-mail address.");
}
else if (txtPemail.Text == "#") //checking for #
{
errorCheck.SetError(txtPemail, "You must enter a valid e-mail address.");
}
else errorCheck.SetError(txtPemail, "");
}
private void txtIid_Validating(object sender, CancelEventArgs e)
{
Match m = Regex.Match(txtIid.Text, #"\b[0-7]{7}\b");
if (m.Success == false)
errorCheck.SetError(txtIid, "Insurance I.D. must be 7 characters.");
else errorCheck.SetError(txtIid, ""); //clear
}
private void txtIcompany_Validating(object sender, CancelEventArgs e)
{
if (txtIcompany.Text == "") //checking for blanks
{
errorCheck.SetError(txtIcompany, "You must enter an Insurance Company.");
}
else errorCheck.SetError(txtIcompany, "");
}
private void txtIphone_Validating(object sender, CancelEventArgs e)
{
if (txtIphone.Text != "Valid")
{
errorCheck.SetError(txtIphone, "Telephone Number must be in proper format");
}
else errorCheck.SetError(txtIphone, "");
}
private void txtIinsured_Validating(object sender, CancelEventArgs e)
{
if (txtIinsured.Text.Length < 4) // checking entry length
{
errorCheck.SetError(txtIinsured, "Please enter the first and last name.");
}
else if (txtIinsured.Text.IndexOf(' ') == -1) //checks for space
{
errorCheck.SetError(txtIinsured, "Must have both names.");
}
else errorCheck.SetError(txtIinsured, "");
}
private void txtDate_Validating(object sender, CancelEventArgs e)
{
if (txtDate.Text == "")
{
errorCheck.SetError(txtDate, "Must enter a correct date.");
}
else errorCheck.SetError(txtDate, "");
}
private void txtPhysician_Validating(object sender, CancelEventArgs e)
{
if (txtPhysician.Text == "") //checking for blanks
{
errorCheck.SetError(txtPhysician, "Must enter the Physician's name.");
}
else errorCheck.SetError(txtPhysician, "");
}
private void txtReason_Validating(object sender, CancelEventArgs e)
{
if (txtReason.Text == "")
{
errorCheck.SetError(txtReason, "Must enter a reason for visit.");
}
else errorCheck.SetError(txtReason, ""); //clears
}
}
}