Program freeze after few days - c#

I created a little program to create a log file to record people's ID number, so far it runs good, no issues or errors, but recently I notice after running for three days it froze another program, until I force closed it. Can anyone take a look to the code to see if there is anything is wrong with it or to improve the code. Thank you.
The programs works with .NET Frameworks 3.5 and is for a Windows XP system, if is possible to make it work with a lower .NET Framework to reduce the installation of additional files.
MainWin form creates a fullscreen window to mask/cover some elements from other software. Is set as topmost to be always be on the top of everything. It has a transparent section with in a text file, then it minimize the window and finally activates a timer. When the timer finish, its maximaze the window again. It has a button to open the LoginWin form and a button to clear the data from the serieBox and return the cursor to the textbox.
LoginWin form is a window to input login information to open the LogFileWin form.
LogFileWin form is a window to read the saved data from the text file in a richTextBox, this data is from the MainWin form. It has a close button and a button to open FolderBrowserDialog to save the text file in another location or to a removable storage device.
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;
namespace LogSerie
{
public partial class MainWin : Form
{
public MainWin()
{
InitializeComponent();
}
private void MainWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void serieBox_KeyDown(object sender, KeyEventArgs e)
{
this.serieBox.MaxLength = 10;
if (e.KeyCode == Keys.Enter)
{
if ((serieBox.Text != ""))
{
if (serieBox.Text == "WLMANTO")
{
StreamWriter B = new StreamWriter("LogfileOperator.txt", true);
B.WriteLine(DateTime.Now + " " + label1.Text + " " + serieBox.Text);
B.Close();
serieBox.Clear();
this.WindowState = FormWindowState.Minimized;
timerManto.Enabled = true;
}
else
{
StreamWriter A = new StreamWriter("LogfileOperator.txt", true);
A.WriteLine(DateTime.Now + " " + label1.Text + " " + serieBox.Text);
A.Close();
serieBox.Clear();
this.WindowState = FormWindowState.Minimized;
timerOperador.Enabled = true;
}
}
}
}
private void timerOperador_Tick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
timerOperador.Enabled = false;
}
private void timerManto_Tick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
timerManto.Enabled = false;
}
private void logButton_Click(object sender, EventArgs e)
{
LoginWin openForm = new LoginWin();
openForm.ShowDialog();
}
private void borrarBut_Click(object sender, EventArgs e)
{
serieBox.Clear();
serieBox.Select();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace LogSerie
{
public partial class LoginWin : Form
{
public LoginWin()
{
InitializeComponent();
}
private void LoginWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void entrarBut_Click(object sender, EventArgs e)
{
if ((usuBox.Text != "") && (contraBox.Text != ""))
{
if ((usuBox.Text == "ADMIN") && (contraBox.Text == "PASS"))
{
LogFileWin openForm = new LogFileWin();
openForm.TopMost = true;
openForm.ShowDialog();
usuBox.Clear();
contraBox.Clear();
this.Close();
}
else
{
MessageBox.Show("Login Incorrect", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void cancelBut_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace LogSerie
{
public partial class LogFileWin : Form
{
public LogFileWin()
{
InitializeComponent();
}
private void LogFileWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void logfileButton_Click(object sender, EventArgs e)
{
string path = #"C:\LogfileOperator\LogfileOperator.txt";
StreamReader stream = new StreamReader(path);
string filedata = stream.ReadToEnd();
richTextBox1.Text = filedata.ToString();
stream.Close();
}
private void closeBut_Click(object sender, EventArgs e)
{
this.Close();
}
private void usbBut_Click(object sender, EventArgs e)
{
string fileName = "LogfileOperator.txt";
string sourcePath = #"C:\LogfileOperator";
using (FolderBrowserDialog ofd = new FolderBrowserDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileName);
sourcePath = Path.Combine(ofd.SelectedPath, fileInfo.Name);
File.Copy(fileName, sourcePath, true);
MessageBox.Show("Logfile Saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}

If you're forced to use this old OS and old framework, you're going to have weird bugs like this. You can maybe work around it by reducing resource usage.
You're constantly creating new copies of your forms LoginWin and LogFileWin, which require OS resources. Instead create one instance of each form and re-use them.
There's also not any exception handling in your code, so you could have problems if files don't exist, or permissions change, or all sort of things. You need to have exception handling and that will give you more information about problems when they occur.
To re-use a form, create an instance as a private field in your class:
public partial class LoginWin : Form
{
// store the LogFileWin form so that we can re-use it
private LogFileWin _logFileWin;
public LoginWin()
{
InitializeComponent();
_logFileWin = new LogFileWin(); { TopMost = true; }
}
private void LoginWin_Load(object s, EventArgs e) { TopMost = true; }
private void entrarBut_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(usuBox.Text) ||
string.IsNullOrEmpty(contraBox.Text))
{
return;
}
if ((usuBox.Text == "ADMIN") &&
(contraBox.Text == "PASS"))
{
// add a reset function to the form
// that makes it ready to display again
_logFileWin.Reset();
// show the dialog
_logFileWin.ShowDialog();
usuBox.Clear();
contraBox.Clear();
this.Close();
}
else
{
MessageBox.Show("Login Incorrect",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void cancelBut_Click(object s, EventArgs e) { Close(); }
}
For exception handling:
public partial class LogFileWin : Form
{
public LogFileWin()
{
InitializeComponent();
}
private void LogFileWin_Load(object s, EventArgs e) { TopMost = true; }
// new function to reset the the dialog to be shown again
public void Reset() { richTextBox1.Text = string.Empty; }
private void logfileButton_Click(object s, EventArgs e)
{
var path = #"C:\LogfileOperator\LogfileOperator.txt";
try
{
// reading from a file can fail, so this
// needs to be wrapped in a try catch
using (var stream = new StreamReader(path))
{
richTextBox1.Text = stream.ReadToEnd();
}
}
catch (Exception ex)
{
var m = String.Format("Unable to read '{0}'; {1}",
path, ex.Message);
MessageBox.Show(message,
"File read error",
MessageBoxButtons.Ok,
MessageBoxIcon.Error);
}
}
private void closeBut_Click(object s, EventArgs e) { this.Close(); }
// we can re-use the folder browser dialog;
// don't need to create a new one every time
FolderBrowserDialog _ofd = new FolderBrowserDialog();
private void usbBut_Click(object sender, EventArgs e)
{
var sourceFileName = "LogfileOperator.txt";
var destFolder = #"C:\LogfileOperator";
var destFileName = string.Empty;
try
{
if (_ofd.ShowDialog() == DialogResult.OK)
{
destFileName = Path.Combine(_ofd.SelectedPath,
sourceFileName);
// every time you do anything with a
// file, it needs to be in a try/catch
// in case the file doesn't exist,
// or the user doesn't have permission.
File.Copy(sourceFileName, destFileName, true);
MessageBox.Show("Logfile Saved",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
// show a message to the user informing them
// of the error and why it occurred.
var m = string.Format("Copy '{0}' to '{1}' failed; {2}",
sourceFileName,
destFileName,
ex.Message);
MessageBox.Show(m,
"File copy error",
MessageBoxButtons.Ok,
MessageBoxIcon.Error);
}
}
}

Related

Save File to .txt after finishing operation

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]);

How to make an login form, my button doesnt do anything

First at all i am new at visual C#. I am trying to make a simple login form with only password login, but when i press button nothing happens. I want to check if there is a user in db which is online.
I dont know where i am making the mistake.
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 SportStat.Forme
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnUlaz_Click(object sender, EventArgs e)
{
ulaz();
}
private void ulaz()
{
if (txtPassword.Text == "")
{
MessageBox.Show("Morate upisati lozinku", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
return;
}
var sql = "select * from users where password='" + txtPassword.Text + "'";
var dt = sustav.puniDt(sql);
if (dt.Rows.Count == 0)
{
MessageBox.Show("Neispravna lozinka", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
if ((string)dt.Rows[0]["password"] != txtPassword.Text)
{
MessageBox.Show("Neispravna lozinka", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
sustav i = new sustav();
i.idUser = (int)dt.Rows[0]["idUser"];
i.pswd = (int)dt.Rows[0]["pswd"];
i.prezimeIme = (int)dt.Rows[0]["prezimeIme"];
i.idKlub = (int)dt.Rows[0]["idKlub"];
int count = i.pswd;
if (count == 1)
{
MessageBox.Show("Login Successful!");
this.Hide();
frmMain fm = new frmMain();
fm.Show();
}
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
Can someone help me with this problem.
Can't comment, too low rep..
Try to put another button on the form and call ulaz(); from that new button.
Sometimes, if you delete button and add them again, or copy paste code, methods get autoassign another name.
For example:
private void btnUlaz_Click(object sender, EventArgs e)
{
ulaz();
}
private void btnUlaz_Click_1(object sender, EventArgs e)
{
ulaz();
}
First one wont work.
I don't know if this is the case in your problem but it's worth trying..

Getting,reading,writing, and saving into one .txt file a collection of .txt documents contents. in visual c# using windows form

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();
}

The process cannot access the file because it is being used by another process

The code that I got was from naudio record sound from microphone then save and many thanks to Corey
This is the error message that I get when I run the code for the second or subsequent times.
The first time it runs, it runs with no issues what so ever.
If I change the file name it works perfectly.
Unable to copy file "obj\Debug\Basque.exe" to "bin\Debug\Basque.exe". The process cannot access the file 'bin\Debug\Basque.exe' because it is being used by another process. Basque
Could someone gave me some guidance to where I'm making my error
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 NAudio.Wave;
namespace Basque
{
public partial class FlashCard : Form
{
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public FlashCard()
{
InitializeComponent();
StopBtn.Enabled = false;
StartBtn.Enabled = true;
}
private void StartBtn_Click(object sender, EventArgs e)
{
StartBtn.Enabled = false;
StopBtn.Enabled = true;
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter(#"C:\Temp\bas0001.wav", waveSource.WaveFormat);
waveSource.StartRecording();
}
private void StopBtn_Click(object sender, EventArgs e)
{
StopBtn.Enabled = false;
waveSource.StopRecording();
}
void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
StartBtn.Enabled = true;
}
private void PlayBtn_Click(object sender, EventArgs e)
{
}
private void ExitBtn_Click(object sender, EventArgs e)
{
}
}
}
It might help to put a Formclosing method with Application.Exit(); in it. If it only works on the first try, it might be because the application isn't fully closing.
You can check if this will fix it when you check task manager. Just make sure that your application isn't still there. Even if it isn't still there, the Application.Exit(); might help.

Why the print Preview doesn't show anything?

I'm having problem with print preview dialog. When I click on print preview, it doesn't show anything I print preview page. I have created a method to setup a preview print output. I can't figure out where did I miss !
below 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;
namespace movieList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
// setup output
Font printFont = new Font("Arial", 14);
//print heading
e.Graphics.DrawString("Select Name", printFont, Brushes.Black, 100, 100);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// terminate application
this.Close();
}
private void clearAllCategoriesToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear all the list of the category
// first we use dialog box for confirmation request
DialogResult confirmDialog = MessageBox.Show("Do you want to delete all category list ?","Clear Category List",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (confirmDialog == DialogResult.Yes)
{
// clearing the comboBox list
categoryComboBox.Items.Clear();
}
}
private void displayTheMovieCategoryCountToolStripMenuItem_Click(object sender, EventArgs e)
{
// count the number of category list
int listCountInteger = categoryComboBox.Items.Count;
MessageBox.Show("There are " + listCountInteger + " categories in the list", "ComboBox Count", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void removeACategoryToolStripMenuItem_Click(object sender, EventArgs e)
{
// remove a category name from list
// first checking if a category has selected
if (categoryComboBox.SelectedIndex == -1)
{
MessageBox.Show("Please Select a Category", "Wrong Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
categoryComboBox.Items.RemoveAt(categoryComboBox.SelectedIndex);
}
}
private void addACategoryToolStripMenuItem_Click(object sender, EventArgs e)
{
// add a category to list
// first checking for no duplicate name
int indexNumberInteger=0;
bool foundNameBoolean=false;
if (categoryComboBox.Text == string.Empty)
{
//empty string has been entered
MessageBox.Show("Please Enter the new category Name !", "Empty Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
while(indexNumberInteger<categoryComboBox.Items.Count && !foundNameBoolean)
{
if (categoryComboBox.Text.ToUpper() == categoryComboBox.Items[indexNumberInteger++].ToString().ToUpper())
{
MessageBox.Show("This Category is already in the list, Please write a new one !", "Duplicate Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
foundNameBoolean = true;
}
}
if (!foundNameBoolean)
{
// add new name to category
categoryComboBox.Items.Add(categoryComboBox.Text);
categoryComboBox.Text = string.Empty;
MessageBox.Show("Category has been updated !");
}
}
}
private void printTheCategoryListToolStripMenuItem_Click(object sender, EventArgs e)
{
// print preview
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
}
}
And preview picture :
Make sure your PrintPage event is wired up.
public Form1() {
InitializeComponent();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
}

Categories

Resources