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";
}
}
}
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 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'
In top of form1 i did
OpenFiledialog openFileDialog1 = new OpenFiledialog();
Then:
private void changeWorkingDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
openFileDialog1.Filter =
"BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
if (result == DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
string directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
}
}
catch (IOException)
{
}
}
}
But when i click the button the init directory is documents and not c: and i don't see the filter/s at all but i see all the files. It's like the settings i did didn't effect.
ShowDialog is modal, so it waits until the user clicks OK/Cancel.
Only then does the rest of your code run.
You should only call ShowDialog after you have finished setting the properties:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg...";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
Your logic is incorrect. You're displaying the dialog before you configure the settings.
// Configure it first
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
// Then show it and wait for the user to make a selection or cancel
DialogResult result = openFileDialog1.ShowDialog();
// Take some action if the user made a selection
if (result == DialogResult.OK)
{
...
As a side note, be careful about eating exceptions. At the least, log the error and inform the user.
catch (IOException ex)
{
// log ex.ToString() somewhere
MessageBox.Show("An error has occurred!\r\n\r\n" + ex.Message);
}
The problem is you are calling ShowDialog() before settings the properties, this should work for you:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
string directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
}
}
catch (IOException)
{
}
}
i want to implement a transaction in my code which is separated by functions.
There is one function in which all other functions are called. I want to make this function execute the function calls in a transaction (All or None).
Some of the function calls are queries while some are routine code for C# and Crystal report.
Can Some one help with this?
This function is working perfectly.
But if 2 users are accessing same database and executing this function at same time may get Cuncurrency problem.
the function code is attached.
public bool Generate_PDF(decimal wo_id)
{
if (Fill_WO_Report_Table(wo_id) == false) // this function has queries
return false;
try
{
string exception;
cryRpt = new ReportDocument();
cryRpt.Load(Application.StartupPath + "\\CrRpt_WO_Report.rpt");
DB_Interface.CrystalReport_Login(ref cryRpt, out exception);
string Temp_file_path = #"c:\Reports\WO_Temp.pdf";
cryRpt.ExportToDisk(ExportFormatType.PortableDocFormat, Temp_file_path);
string File_name = str_WO_File_Name + ".pdf";
// option to print at which location
//DialogResult dlg = MessageBox.Show("Select Option For Print :\n\nYes - Print To Default Path\nNo - Print To Custom Path\nCancel - Do Not Print",
// "Print GRN", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
SaveToDialog frm = new SaveToDialog(ref File_name);
DialogResult dlg = frm.ShowDialog();
File_name = frm.GetString();
frm.Dispose();
frm = null;
if (dlg == DialogResult.Yes)
{
if (Convert.ToString(MMS_Vars.PathReport_WO) == "")
throw new Exception("Default Path Not Available.");
string Full_File_name = Convert.ToString(MMS_Vars.PathReport_WO) + "\\" + File_name;
cryRpt.ExportToDisk(ExportFormatType.PortableDocFormat, Full_File_name);
System.Diagnostics.Process.Start(Full_File_name);
}
else if (dlg == DialogResult.No)
{
SaveFileDialog obj_saveFileDialog = new SaveFileDialog();
obj_saveFileDialog.InitialDirectory = Convert.ToString(MMS_Vars.PathReport_WO);
//obj_saveFileDialog.RestoreDirectory = true;
obj_saveFileDialog.FileName = File_name; //set file name to
obj_saveFileDialog.Filter = "PDF Files|*.pdf";
DialogResult result = obj_saveFileDialog.ShowDialog();
if (result == DialogResult.OK && obj_saveFileDialog.FileName != "")
{
cryRpt.ExportToDisk(ExportFormatType.PortableDocFormat, obj_saveFileDialog.FileName);
System.Diagnostics.Process.Start(obj_saveFileDialog.FileName);
}
else if (result == DialogResult.Cancel)
{
obj_saveFileDialog.Dispose();
cryRpt.Close();
cryRpt.Dispose();
return false;
}
obj_saveFileDialog.Dispose();
}
else if (dlg == DialogResult.Cancel)
{
cryRpt.Close();
cryRpt.Dispose();
return false;
}
cryRpt.Close();
cryRpt.Dispose();
// Drop Report tables
if (Drop_WO_Report_Table() == false) // this function has queries
return false;
return true;
}
catch (Exception exe)
{
MessageBox.Show(exe.Message, "WO Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
You haven't posted any of the functions you do on your db. Are there any writes, etc? From your posted code, adding a transaction will probably not solve your problem. A simple solution can be to add a lock around the function so only one pdf is created at a time:
private static object locker = new object();
public bool Generate_PDF(decimal wo_id)
{
lock(locker){
if (Fill_WO_Report_Table(wo_id) == false) // this function has queries
return false;
........
........
return true;
}
catch (Exception exe)
{
MessageBox.Show(exe.Message, "WO Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}//END LOCK
}
When I click the button to open a file the OpenFileDialog box opens twice. The first box only opens the image files and the second box text files. If the user decides to close out the first box without choosing a file the second box pops up as well. I'm not sure what I am over looking on this issue. Any help would be appreciated. Thanks!
OpenFileDialog of = new OpenFileDialog();
of.Filter = "All Image Formats|*.jpg;*.png;*.bmp;*.gif;*.ico;*.txt|JPG Image|*.jpg|BMP image|*.bmp|PNG image|*.png|GIF Image|*.gif|Icon|*.ico|Text File|*.txt";
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
image1.Source = new BitmapImage(new Uri(of.FileName));
// enable the buttons to function (previous page, next page, rotate left/right, zoom in/out)
button1.IsEnabled = false;
button2.IsEnabled = false;
button3.IsEnabled = false;
button4.IsEnabled = false;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
}
catch (ArgumentException)
{
// Show messagebox when argument exception arises, when user tries to open corrupted file
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
using (StreamReader sr = new StreamReader(of.FileName))
{
textBox2.Text = sr.ReadToEnd();
button1.IsEnabled = true;
button2.IsEnabled = true;
button3.IsEnabled = true;
button4.IsEnabled = true;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
}
}
catch (ArgumentException)
{
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
You're calling ShowDialog() twice:
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//...
}
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
Just call it once, and save the results:
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//...
}
// Note that the condition was the same!
else if(dialogResult != System.Windows.Forms.DialogResult.OK)
Edit:
If you want the second dialog to only show when the first is handled, you can do:
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//...
// Do second case here - Setup new options
dialogResult = of.ShowDialog(); //Handle text file here
}
You are calling ShowDialog both in the if and else if condition. That method is responsible for showing the dialog and only has the nice side effect of also telling you what the user clicked.
Store the method's result in a variable and check that in your if..elseif conditions instead.