I am to create a program that reads from an outputfile AND also add FURTHER text to that output file trough "AppendText" method so that nothing in the text file is overriden. You can add things to the listbox via a textbox, but what I am trying to do is to prevent duplicate entries. I have implmeneted a code that does supposedly prevents multiple entries, but it doesn't work properly. It gives a message that I set "Duplicate entry" but it still adds the entry. ANY WAY TO FIX THIS? Please Help THANKS.
This is the 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;
namespace BIT_UNITS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void displayButton_Click(object sender, EventArgs e)
{
try
{
//Variables
string unitsList;
//declare streamReader variable
StreamReader inputFile;
//Open file & get units list
inputFile = File.OpenText("BITS_Units.txt");
//Clear anything currently in the listbox
unitsListBox.Items.Clear();
//Read the file's Contents
while (!inputFile.EndOfStream)
{
//Get Units List
unitsList = inputFile.ReadLine();
//Display the units list in the listbox
unitsListBox.Items.Add(unitsList);
}
//close the file
inputFile.Close();
}
catch
{
MessageBox.Show("Error");
}
}
private void addUnitButton_Click(object sender, EventArgs e)
{
try
{
//Declare streamwriter variable
StreamWriter outputFile;
//Open file and get a streamwriter object
outputFile = File.AppendText("BITS_Units.txt");
//Record inputs to the file
outputFile.WriteLine(addUnitsTextBox.Text);
//Close the file
outputFile.Close();
//Determine wether textbox is filled
if (addUnitsTextBox.Text== Text)
{
//Display message
MessageBox.Show("Unit was successfully added.");
}
//Determine wether textbox is filled
if (addUnitsTextBox.Text == "")
{
MessageBox.Show("Please enter a unit name to add to the list.");
}
if (unitsListBox.Items.Contains(addUnitsTextBox.Text))
{
MessageBox.Show("This unit already exists");
}
else
{
unitsListBox.Items.Add(addUnitsTextBox.Text);
addUnitsTextBox.Text = "";
}
}
catch (Exception)
{
MessageBox.Show("error");
}
}
private void clearButton_Click(object sender, EventArgs e)
{
try
{
//Clear data
addUnitsTextBox.Text = "";
unitsListBox.Items.Clear();
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
//Close the form
this.Close();
}
}
}
Before adding item to list box, check if doesn't exist in the list box.
if (!unitsListBox.Items.Contains(unitsList) )
{
unitsListBox.Items.Add(unitsList);
}
Related
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);
}
}
}
I am able to read my text file however when I go and click my edit button it moves all the current rows in the text file to the top row and doesn't update anything. Also how would I go about adding a row to the text file without moving the rows?
private void btnEdit_Click(object sender, EventArgs e)
{
BugTrackers cs = Bugs[index];
// DisplayBugs();
// Update datafile
UpdateBugsInfo();
}
private void UpdateBugsInfo()
{
if (lstBugs.SelectedIndex > -1)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter("smBugs.txt", false);
for (int i = 0; i <= Bugs.Count - 1; i++)
{
sw.Write(Bugs[i].BugsName);
sw.Write(",");
sw.Write(Bugs[i].BugsDesc);
}
sw.Close();
}
}
The StreamWriter object you are creating is having wrong parameter value for append. You need to set that as true OR just remove that parameter since it’s default value is true.
System.IO.StreamWriter sw = new System.IO.StreamWriter("smBugs.txt", true);
OR
System.IO.StreamWriter sw = new System.IO.StreamWriter("smBugs.txt");
Here is the link from Microsoft.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=netframework-4.7.2#System_IO_StreamWriter__ctor_System_String_System_Boolean_
You are also not using the using statement, which ensures the StreamWriter object is removed from memory when no longer needed. Please go through this article to understand it better.
https://www.dotnetperls.com/streamwriter
Hope this helps!
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 BugTracker
{
struct BugTrackers
{
public string BugsName;
public string BugsDesc;
}
public partial class YoungKidsBugTracker : Form
{
// Field to hold a list of BugTrackers objects
private List<BugTrackers> Bugs = new List<BugTrackers>();
private int index; // index fo selected bugs in combobox
public YoungKidsBugTracker()
{
InitializeComponent();
}
private void ReadFile()
{
try
{
//Declare a varialble to hold Bugs Name
StreamReader inputFile; // To Read the file
string line; // To hold a line from the file
// Create an instance of the Bug Accounts
BugTrackers entry = new BugTrackers();
// Create a delimeter array
char[] delim = { ',' };
// Open the file and get a StreamReader Object
inputFile = File.OpenText("smBugs.txt");
// Read the file's contents
while (!inputFile.EndOfStream)
{
// Read a line from the file
line = inputFile.ReadLine();
// Tokenize the line
string[] tokens = line.Split(delim);
// Stores the tokens in the entry object
entry.BugsName = tokens[0];
entry.BugsDesc = tokens[1];
// Add the entry object to the combobox
Bugs.Add(entry);
}
// Close the File
inputFile.Close();
}
catch (Exception ex)
{
// Display an error message
MessageBox.Show(ex.Message);
}
}
private void lstBugs_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the index of the sselected item
index = lstBugs.SelectedIndex;
// Display Bug Information
DisplayBugs();
}
private void DisplayBugs()
{
//Show Data
txtBugsName.Text = Bugs[index].BugsName;
rtxtBugDesc.Text = Bugs[index].BugsDesc.ToString();
}
private void YoungKidsBugTracker_Load(object sender, EventArgs e)
{
// Read the Bugs.txt file
ReadFile();
// Display Bug Information
BugNameDisplay();
}
private void btnEdit_Click(object sender, EventArgs e)
{
BugTrackers cs = Bugs[index];
// DisplayBugs();
// Update datafile
UpdateBugsInfo();
}
private void UpdateBugsInfo()
{
if (lstBugs.SelectedIndex > -1)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter("smBugs.txt");
for (int i = 0; i <= Bugs.Count - 1; i++)
{
sw.Write(Bugs[i].BugsName);
sw.Write(",");
sw.WriteLine(Bugs[i].BugsDesc);
// sw.Write(Environment.NewLine);
}
sw.Close();
}
}
private void BugNameDisplay()
{
// Display the list of Bug Names in the List Control
foreach (BugTrackers entry in Bugs)
{
lstBugs.Items.Add(entry.BugsName );
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
}
}
}
This is the code in its entirety. I have a list box with 2 text boxes to hold the bug name and description. I have 3 buttons Add, Edit and Delete. If an item is selected from the listbox it will display the bugname and description. If the entry needs updated changes are made and will change the information needed. If a new bug is added you would use the add button same for the delete button.
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();
}
Am working in a project where I should give a crystal reports RPT file as input and get the properties of that report.
I am facing a problem in loading the report itself so I have used isLoaded() function to check whether the report is loaded or not.
I have used the following 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;
using System.Web;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace sampleretreival
{
public partial class Form1 : Form
{
public string flName;
public Form1()
{
InitializeComponent();
Retrieve.Enabled = false;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFiles.SelectedItems.Count > 0)
{
Retrieve.Enabled = true;
}
else
{
Retrieve.Enabled = false;
}
}
private void Browse_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = false;
openFileDialog1.Filter = "Crystal Report Files | *.rpt";
openFileDialog1.ShowDialog();
flName = openFileDialog1.FileName;
if (flName.Length != 0)
{
lstFiles.Items.Insert(0, flName);
Retrieve.Enabled = true;
}
else
{
MessageBox.Show("Please select the crystal report files for analysis.", "SAMPLE", MessageBoxButtons.OK, MessageBoxIcon.Information);
Browse.Focus();
}
}
private void Retrieve_Click(object sender, EventArgs e)
{
int a=1;
ReportDocument rpt = new ReportDocument();
rpt.Load(flName);
int count = 5;
if (rpt.IsLoaded)
{
MessageBox.Show(count.ToString());
}
else
{
MessageBox.Show(a.ToString());
}
}
}
}
After compiling, I clicked the Browse button to select the report from the disk but when I click Retrieve button, the program keeps on running. I am not getting any output or any error.
I have this Code in Form1. Im doing a search for xml files. When i find them im using listBox1 selected index changed event and i want to do that when i select item in the lixtBox it will consider it as a file will parse it content and show me the parsed content.
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.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DirectoryInfo dirinf = new DirectoryInfo(#"C:\");
List<FileSystemInfo> fsi = new List<FileSystemInfo>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
private void ParseAndDisplayXml(string filename)
{
XDocument document = XDocument.Load(filename);
var list = document.Root.Elements("Message")
.Select(
e => new
{
Date = e.Attribute("Date").Value.ToString(),
Time = e.Attribute("Time").Value.ToString(),
Text = e.Element("Text").Value.ToString()
}
);
string result="";
foreach (var item in list)
{
result += string.Format("Date--{0},Time--{1},Text--{2}", item.Date, item.Time, item.Text + Environment.NewLine);
}
}
public void Search(string strExtension,
DirectoryInfo di,
List<FileSystemInfo> pResult)
{
try
{
foreach (FileInfo fi in di.GetFiles())
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => label2.Text = fi.Name));
}
if (fi.Name == "MessageLog.xsl")
{
foreach (FileInfo fii in di.GetFiles())
{
if (fii.Extension == strExtension)
pResult.Add(fii);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => label4.Text = pResult.Count.ToString() + Environment.NewLine));
}
}
}
foreach (DirectoryInfo diChild in di.GetDirectories())
Search(strExtension, diChild, pResult);
}
catch (Exception e)
{
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Search(".xml", dirinf, fsi);
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
for (int i = 0; i < fsi.Count; i++)
{
listBox1.Items.Add(fsi[i].Name + Environment.NewLine);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = listBox1.SelectedItem.ToString();
}
}
}
Im starting the search from C:\
Then when the search so over completed im adding the items it found to the listBox1.
For example now in my listBox1 i have 4 files:
danny.xml
adi.xml
sharon.xml
yoval.xml
In the selectedindexchanged i added option so the user can move between the items.
Now what i want to do is when the user select some index for example index [1] in the listBox and only if he clicked enter with the keyboard or clicked with the mouse left click it will call/use the function: ParseAndDisplayXML.
Then it will parse the selected index wich need to be translated to a file so in the backgroundWorker1_RunWorkerCompleted event i madding the files to the listBox as items but only with the names of the files. If i did .FullName instead .Name it was adding the files names with the directories too.
So i need somehow to get the FullName of the files in the completed event i think then when selecting one of the FullName items to parse it and display it in the listBox.
The parse function should take the specific content from the xml files and it worked i checked this function before alone.
The problem is how do i make that the user will select the index by click/key enter and how to parse and display it ?
When you add something to a listbox.
It expects an object, and sets the text to object.ToString()
e.g.
MyListBox.Add(100);
Would box 100 and display "100"
Couldn't find if FileSystemInfo's ToString() method has been overridden but first thing to try would be
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// newline is unnecesary and you should be using foreach
foreach(FileSystemInfo f in fsi)
{
listBox1.Items.Add(f);
}
}
// display full name of file
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = ((FileSystemInfo)listBox1.SelectedItem).Fullname;
}
If FileSystemInfo.ToString() doesn't return Name, there are a few ways to deal with that.
If you don't want to hold on to the FileSystemInfo instances, we can deal with that too.