I have a program that start work. I can open and store files. But when I open a file (e.g. File 1) the program reads it and than when I want to open a second file (e.g. File 2) I get errors.
Opening files goes with bindingSource.DataSource I assume the issue is there but I have tried to set it to Null but that give other errors.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
string CheckConnection;
_bindingSource.DataSource = null;
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "XML File (*.xml)|*.xml";
ofd.Title = "Open Client Profile File";
if (ofd.ShowDialog() == DialogResult.OK)
{
lblCompanyName.Enabled = true;
lblClientNumber.Enabled = true;
lblSiteName.Enabled = true;
lblMachineTotal.Enabled = true;
lblImo.Enabled = true;
cmbMachineName.Enabled = true;
lblPower.Enabled = true;
lblMachineType.Enabled = true;
lblFrequency.Enabled = true;
lblSpeed.Enabled = true;
//Deserialize
_root = HelperXml.DeserializeXMLFileToObject<XmlRoot>(ofd.FileName);
ClientFileName = ofd.FileName; //Store current filename
lblCompanyName.ForeColor = Color.Black;
lblCompanyName.Text = "Company Name: " + _root.CompanyProfile.CompanyName;
lblSiteName.Text ="Sitename: " + _root.CompanyProfile.SiteName;
lblImo.Text = "IMO: " + _root.CompanyProfile.Imo.ToString();
lblMachineTotal.Text = "Machine Total: " + _root.CompanyProfile.MachineTotal.ToString();
lblClientNumber.Text = "Clientnumber: " + _root.CompanyProfile.ClientNumber.ToString();
_bindingSource.DataSource = _root.MachineProfiles.ToList();
cmbMachineName.DataSource = _bindingSource;
lblPower.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.NominalPower));
lblFrequency.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.Frequency));
lblMachineType.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.TypeDescription));
lblSpeed.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.NominalSpeed));
_bindingSource2.DataSource = _root.MachineMeasurements.ToList();
dataGridView1.DataSource = _bindingSource2;
dataGridView1.DataBindings.Add("Text", _bindingSource2, nameof(MachineMeasurement.MeasurementDate));
}
}
CheckConnection = statusLblDevice.Text.ToString();
//Enable "ImportData" button function only when a clientfile has been loaded and a device has been detected.
if (CheckConnection.Contains("VM25")== true && lblSiteName.Text != null)
{
importDataToolStripMenuItem.Enabled = true;
}
}
Above is the code that opens a file this is connected to other classes but I think there is not the issue. I think prior to run this code all should be empty or so.
Does anybody know how I could do this?
Without adding any code I get this error:
System.ArgumentException: 'This causes two bindings in the collection to bind to the same property.
This is the error message I get when I added the code for making the bindingSource null
System.ArgumentException: 'Cannot bind to the property or column NominalPower on the DataSource.
Parameter name: dataMember'
Related
Hello im having trouble with file dialog
Standard code, but it's freezing while selecting large files (600MB+ xls file that i need to first reformat to xlsb, then stream data from, but that is not important here).
What i wanted to achieve is to hide dialog when Open button is clicked, so that i could display Loading Message.
Yet im not sure how can i achieve that. Can i somehow subscribe to Open button?
OpenFileDialog openFile = new OpenFileDialog() { DereferenceLinks = false };
openFile.Title = "Select Supplier List";
openFile.Filter = "Excel files (*.*xls*)|*.*xls*";
try
{
if (openFile.ShowDialog() == true)
{
/* Takes long time to go after selection */
ViewModel.ReportPath = openFile.FileName;
ViewModel.FileTrueName = Path.GetFileName(ViewModel.ReportPath);
}
}
catch
{
ViewModel.ReportPath = null;
ViewModel.FileTrueName = null;
}
Wrapping code with task, helped :)
Some changes happened during searching for answer, based on comments.
Task.Run(() =>
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "Select Supplier List";
openFile.Filter = "Excel Files(*.xls; *.xlsx; *.xlsb; *.xlsm)| *.xls; *.xlsx; *.xlsb; *.xlsm";
try
{
if (openFile.ShowDialog() == true)
{
ViewModel.ReportPath = openFile.FileName;
ViewModel.FileTrueName = Path.GetFileName(ViewModel.ReportPath);
}
}
catch
{
ViewModel.ReportPath = null;
ViewModel.FileTrueName = null;
}
});
I have tesseract installed and I am using button click to set location of tesseract.exe file. I am also using another button click to set the location of the image file. Now I want the third button click to process the image with tesseract as I have stored their respective locations.
I am using some basic crude approach but it suits me.
My code is like:
private void B8_Click(object sender, EventArgs e)
{
q = z + "\\" + "output.txt";
if (k != null)
{
Process pr = new Process();
pr.StartInfo.FileName = j;
pr.StartInfo.Arguments = k + " " + q;
pr.Start();
pr.WaitForExit();
}
else
{
MessageBox.Show("No Image File Selected.");
}
var filetext = File.ReadAllText(q);
tb5.Text = filetext;
//File.Delete(q);
}
private void B10_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
j = "\"" + openFileDialog1.FileName + "\"";
MessageBox.Show("Tesseract Location Set: " + j);
}
}
private void B9_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
k = "\"" + openFileDialog1.FileName + "\"";
MessageBox.Show("Image File Location Set: " + k);
}
}
My 3-button click story so far:
I have successfully run the code with 1-button to set the tesseract.exe path, 2-button to set the image path, but the 3-button (see B-8) has an issue.
It extracts the text and stores into an "output.txt" file. But, I am not able to import this text into my textbox tb5 and then destroy this file.
The error I am getting is Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Could not find file 'C:\Users\ambij\Desktop\try\output.txt'.
I don't understand this but there is actually output.txt file residing in the folder.
The following is for Tesseract 3.05.02 - May work in a later version
private void RunIt()
{
string tessDataPath = yourTessDataPath; // Your Tesseract Location Set
string imagePath = yourImagePath; // The Image File Location
string theTextFromTheImage = DoOCR(yourTessDataPath, yourImagePath);
// Some formatting may be required - OCR isn't perfect
MessageBox.Show(theTextFromTheImage);
}
private string DoOCR(string tessdataPath, string filePath)
{
string returnText = "";
using (var engine = new TesseractEngine(tessdataPath, "eng", EngineMode.Default))
{
// engine.SetVariable("tessedit_char_whitelist", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Only regular letters
string theVersion = engine.Version; // Optional, but useful
using (var img = Pix.LoadFromFile(filePath))
{
using (var page = engine.Process(img))
{
returnText = page.GetText();
}
}
}
return returnText;
}
Im trying to use the openFileDialog to load in 2 different files that goes to 2 different area. I trying doing 2 ways, first i try adding an if statement to see which file they select and use that expression, but it gives me an error.
OpenFileDialog opendi = new OpenFileDialog();
opendi.Filter = "xml|*.xml";
if (opendi.ShowDialog() == DialogResult.OK)
{
if (opendi.FileName == Hotel_Filename)
{
hotelListData = HotelList.HotelLoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
}
else
{
rmtp = roomtypedata.LoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
and if i do this way , it works, but i have to load the files in the right order, or else if i load the 2nd one first , i get an error. so is there a better method to this?
OpenFileDialog opendi = new OpenFileDialog();
opendi.Filter = "xml|*.xml";
if (opendi.ShowDialog() == DialogResult.OK)
{
hotelListData = HotelList.HotelLoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
if (opendi.ShowDialog() == DialogResult.OK)
{
rmtp = roomtypedata.LoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
Ok, the problem seems to be with checking the file name. You want to compare only the file name,not all the path. Try this:
Hotel_Filename = "hotels.xml"
....
for (int=0;i<2;i++)
{
OpenFileDialog opendi = new OpenFileDialog();
opendi.Filter = "xml|*.xml";
if (opendi.ShowDialog() == DialogResult.OK)
{
if (Path.GetFileName(opendi.FileName) == Hotel_Filename)
{
hotelListData = HotelList.HotelLoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
else
{
rmtp = roomtypedata.LoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
}
}
Hi I have a webpage that is on my computer that I want to open it in a web browser in a visual c# windows form program in visual studio here is what I have tried
private void openWebPageToolStripMenuItem_Click(object sender, EventArgs e)
{
int size = -1;
openFileDialog2.InitialDirectory = "C://";
openFileDialog2.Filter = "HTML files (*.html)|*.html|All files (*.*)|*.*";
openFileDialog2.FilterIndex = 2;
openFileDialog2.RestoreDirectory = true;
openFileDialog2.Multiselect = false;
openFileDialog2.Title = "Open HTML File";
DialogResult result = openFileDialog2.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog2.FileName;
try
{
string htmlfile = File.ReadAllText(file);
size = htmlfile.Length;
filelocation = openFileDialog2.FileName;
Form2 frm2 = new Form2();
frm2.Show();
string a = openFileDialog2.FileName;
this.webBrowser1.Url = new System.Uri("file:///" + a, System.UriKind.Absolute);
}
catch (IOException)
{
}
right now it give an error that says
Script error an error has occurred in the script on this page. line:383 Char: 3 error: Object doesn't support property or method 'keys' code:0 url: File:///c:/Users/[username]%20[username]/Desktop/Webpage/Processing%20Js%20Webpage/Processing.js Do you want to continue running scripts on this page?
I'm stuck and cant think of what to do and some help would be nice thanks.
My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}