|
Well I did try to help, by suggesting a class that would make your application much easier to manage. But if you want to dismiss it out of hand that is fine with me.
|
|
|
|
|
For your Info (if you don't know it) : with Richard you got one of the most famous members of this forum. I would suggest that you try to understand what he has suggested to you :
You can also create a Class which contains different information. This Class could be added as well to your ListBox and allows you to do what you are missing in the moment. Perhaps you re-think this ...
|
|
|
|
|
|
Member 13489244 wrote: OpenFileDialog openFileDialog1
Perhaps there is an incorrect assumption here.
If you get a list of files from a file dialog you cannot "move" anything.
That list of files represent real resources on the OS. If you want to move a file (not an entry in the list) then you must move it. And the only way you can "move" it is by changing the directory.
If you want to change the order in a directory you must rename it.
And regardless of what you are doing if you modify the file name or location then you need to requery the OS for an updated list of files. You shouldn't attempt to modify the list yourself.
Alternatively perhaps you want to order the list based on criteria that the OS does not know about. That however is much more complicated and it REQUIRES that you store files and the additional data is some persistent data store (file, database, etc.) You would then load that, load the current file list from the OS, correlate the two and then with a brand new list that you created manage the files themselves and associated data for each file. On exit you would then update your persistent data store with changes.
|
|
|
|
|
Use an ObservableCollection as the data source for your listbox.
ObservableCollection has a "move" command:
.Move( oldIndex, newIndex )
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Than you for taking the time to look over my problem.
I'm trying to make a playlist in c# that will allow me to play music. Below is the code that I have so far. I have the ability to add files from a fold and play they on the media player. However the issue is when I add additional music files is gives me an error message that reads IndexOutOfRange. So my question is: How can I add music files to a listbox than add some mote music files and be able to play them?
public MusicBox()
{
InitializeComponent();
}
private void btnFiles_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = openFileDialog1.SafeFileNames;
paths = openFileDialog1.FileNames;
for (int i = 0; i < files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = paths[listBox1.SelectedIndex];
}
|
|
|
|
|
Use the debugger: check the value of listBox1.SelectedIndex and the number of items in paths
Either listBox1.SelectedIndex will be too big, or it will be negative.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
You're appending the new files to the list, but replacing the paths variable with the new paths.
So, for example, if you've already selected files A, B and C:
List = { A, B, C }
Paths = { A, B, C }
and you then select D and E:
List = { A, B, C, D, E }
Paths = { D, E }
if you try to play A, you'll get D; if you try to play B, you'll get E; if you try to play anything else, you'll get an IndexOutOfRangeException .
If you want to replace the list of files, you'll need to call listBox1.Items.Clear() before adding the new files.
If you want to append the list of files, you'll need to append them to the paths list as well. The simplest option would probably be to change it to be a List<string> instead of an array:
private readonly List<string> paths = new List<string>();
private void btnFiles_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
paths.AddRange(openFileDialog1.FileNames);
string[] files = openFileDialog1.SafeFileNames;
for (int i = 0; i < files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming ,
You sir are my hero!!! Thank you so much
|
|
|
|
|
Never use "SelectedIndex" unless you know its value first.
The default is "-1"; which means "not selected"; and always results in an invalid index.
(And SelectedIndex will "bounce around" prior to a form / window being fully loaded).
Just because a "list control" has items, does not mean that SelectedIndex is "in range".
That also goes for "SelectedItem", "CurrentItem", "Position", etc. when dealing with "lists" and navigation.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Hello,
I am new to C# and has been assigned a task to modify a code.
One of our Reporting Tool is fetching the data from our Historian server and generating the report in excel format. But time taken for the generation of each report is around 15-20 mins depending upon the size of data. But this time should be less.
So, the developer of the Tool told us to try by our own exporting the data to .csv format. I tried it and changed the format to .csv but the time did not reduced.
I am attaching the part of our code:
private void export_to_excel(string template)
{
try
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkBook = excelApp.Workbooks.Open(path + "Report.xltx");
Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkBook.Sheets["Report"];
string excelfile = IniReadValue("TemplateDetails", "ExpPath", SlTemplate.Text) + template +"_" + Fdt.Text.Replace('/', '_').Replace('-', '_').Replace(' ', '_').Replace(':', '_') + ".xlsx";
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Range range;
int j = 0, k = 0, i = 0, l = 0,m=0;
for (k = 0; k < dt.Rows.Count; k++)
{
i = 0;
for (j = 0; j < dt.Columns.Count; j++)
{
if (stat == false)
{
excelWorkSheet.Cells[9 + k, j + 2] = dt.Rows[k].ItemArray[j].ToString();
}
else
{
if(j==0)
{
excelWorkSheet.Cells[9 + k, i + 2] = dt.Rows[k].ItemArray[j].ToString();
}
else if(dt.Columns[j].ColumnName.Contains("C"))
{
excelWorkSheet.Cells[9 + k, i + 3] = dt.Rows[k].ItemArray[j].ToString();
if (dt.Columns.Contains("C" + i.ToString()))
{
if (dt.Rows[k]["S" + i.ToString()].ToString().ToUpper() != "GOOD" & (dt.Rows[k]["S" + i.ToString()].ToString() != ""))
{
range = excelWorkSheet.get_Range(Number2String(9 + k) + (k + 9).ToString(), Number2String(i + 3) + (k + 9).ToString());
range.Cells.Font.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbRed;
}
}
i++;
}
}
}
}
excelApp.DisplayAlerts = false;
for (m = 4; m < ((j + 3)/2); m++)
{
if (m < j + 1)
{
if (excelWorkSheet.Cells[9, m].Value.ToString() == excelWorkSheet.Cells[9, m + 1].Value.ToString())
{
l++;
}
else
{
if (l > 0)
{
range = excelWorkSheet.get_Range(Number2String(m - l) + "9", Number2String(m) + "9");
range.Merge();
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
}
l = 0;
}
}
else
{
if (l > 0)
{
range = excelWorkSheet.get_Range(Number2String(m - l) + "9", Number2String(m) + "9");
range.Merge();
}
l = 0;
}
}
excelWorkSheet.Cells[5, 5] = IniReadValue("TemplateDetails", "Substation", SlTemplate.Text);
excelWorkSheet.Cells[6, 5] = IniReadValue("TemplateDetails", "Region", SlTemplate.Text);
excelWorkSheet.Cells[7, 5] = Fdt.Text;
string alph = "A";
if(stat==false)
{
alph = Number2String(j + 1);
}
else
{
alph = Number2String(Convert.ToInt16(Math.Abs(Convert.ToDouble((j + 4) / 2))));
}
range=excelWorkSheet.get_Range("B9", alph + (dt.Rows.Count + 8).ToString());
range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range = excelWorkSheet.get_Range("C12", alph + (dt.Rows.Count + 3).ToString());
range.NumberFormat = "General";
excelWorkSheet.Cells[12 + k, 1] = "Remarks:";
range = excelWorkSheet.get_Range("A"+(12 + k).ToString() ,"E"+ (14 + k).ToString());
range.Merge();
for (j = 0; j < pntid.Count; j++)
{
excelWorkSheet.Cells[49+j, 2] = DGSet[j];
excelWorkSheet.Cells[49+j, 3] = dgval[j];
excelWorkSheet.Cells[49+j, 2].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
excelWorkSheet.Cells[49+j, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
}
range = excelWorkSheet.get_Range("B49", "C"+ (49+j-1).ToString());
range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
range.Cells.WrapText = true;
range = excelWorkSheet.get_Range("B49");
range.EntireColumn.AutoFit();
excelWorkSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait;
excelWorkSheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA3;
Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkBook.Sheets["Chart"];
if (graph.Checked == true)
{
Microsoft.Office.Interop.Excel.ChartObject chartObject11 = (Microsoft.Office.Interop.Excel.ChartObject)excelWorkSheet1.ChartObjects(1);
chartObject11.Activate();
Microsoft.Office.Interop.Excel.Chart chartPage = chartObject11.Chart;
range = excelWorkSheet.get_Range("B9", alph + (dt.Rows.Count + 3).ToString());
excelApp.ActiveChart.SetSourceData(range, Microsoft.Office.Interop.Excel.XlRowCol.xlColumns);
excelWorkSheet1.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait;
excelWorkSheet1.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA3;
}
else
{
excelWorkSheet1.Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden;
}
excelWorkBook.SaveAs(excelfile, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
excelWorkBook.Close();
excelApp.Quit();
releaseObject(excelWorkSheet);
releaseObject(excelWorkBook);
releaseObject(excelApp);
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Equals("EXCEL"))
clsProcess.Kill();
}
}
catch (Exception err)
{
fail = fail+1;
ErrorLog(DateTime.Now.ToString() + "----- Export to excel ---" + err.ToString()); ;
}
}
Can anyone please help me getting out of the situation with or without using interop.excel.
Thanks in Advance,
Rohit
|
|
|
|
|
If you do it in the way as showed inside your code you could save it as XLS-File.
Your time comes from using Excel per "remote"-access.
When you want to export your data to a CSV-File you use the Standard-Features from .Net to create a Text-File with the Extension 'CSV'. Different Cells/Entries are seperated with a Comma or Semicolon. This kind of writing data will be very much faster ...
|
|
|
|
|
Thanks Ralf for the reply,
Can you please add the codes (of course if possible) or give some hint to dump to .txt.
Or you can suggest some similar threat.
Thanks,
Rohit
|
|
|
|
|
I suggest you ask Google for this - 'C# write CSV' for example.
Now you will get a lot of Results - you should look by yourself which matches best to your requirement (because I think you must also learn how to use the commands) and how to create the Method you really need ...
|
|
|
|
|
Ok Thanks,
I will try searching for the similar threads.
|
|
|
|
|
Trying to export this as CSV is unlikely to work, since you create so much information that needs to be in specific Excel format, which you cannot express in .csv. You need to look at the actual code that is extracting and converting individual items from the input data. It may be that you could get that in a simpler format, as some of your expressions seem over complex.
|
|
|
|
|
A lot of that is going to be his client's expectations. It may be that it is a data load and .csv would work better anyway. I definitely agree he will lose all formatting placing in a .csv.
modified 27-Oct-17 11:08am.
|
|
|
|
|
Looking at his code I do not see how he could even begin to think about creating .csv file(s). The whole thing is so tightly connected to Excel it would need a complete redesign. And that would still not produce the results they want.
|
|
|
|
|
Excel interop is notoriously slow. Try using a library which generates the file directly instead - eg:
If you still want to try CSV, and abandon the features which aren't supported in that format, there are various libraries available to help - for example, CsvHelper[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I just want to second Richard. I've used OpenXML a few times and have always been happy with it.
There's enough shake-and-bake examples on the net to make getting started with it fairly easy, as well.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
The only problem with OpenXML is a somewhat steep learning curve for someone admittedly new to C#. I agree it is a great solution to the problem, though.
I have used Microsoft.VisualBasic.IO to import .csv files, and it has the ability to export to .csv as well. Importing was extremely quick. To use it you will have to do the following:
Add a reference in code to FileIO:
using Microsoft.VisualBasic.FileIO;
You will need to add a reference to the assembly. The steps are (Framework 4.5, VS Pro 2013):
Open the Project menu
Select Add Reference
Open Framework
Checkmark Microsoft.VisualBasic
You can then use a FileSystem class method called OpenTextFileWriter or WriteAllText to put text into a .csv.
|
|
|
|
|
It's a deep hole that is getting deeper.
"Magic numbers", and combined with the fact that "you are new to C#", this is a sad way to start.
Should've used VBA, or exported to CSV via "Save as...".
Even the original Excel choice may have been wrong.
One needs help from someone with some common sense and experience.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Gerry Schmitz wrote: some common sense and experience. Yes, you might find some in QA.
|
|
|
|
|
I have a Windows forms program that crashes every time I turn off the monitor, minimize the form, or perform an update on the form. I seem to be able to Update() individual objects on the form without any issue, but repainting the entire form causes the following error:
Quote: System.ArgumentException was unhandled
HResult=-2147024809
Message=Parameter is not valid.
Source=System.Drawing
StackTrace:
at System.Drawing.Image.get_RawFormat()
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle rect)
at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
InnerException:
As you can see, none of the trace refers to my code, but to System.Drawing dll. Here is the code I used to attempt to isolate the problem and produce this message:
try
{
if (WindowState != FormWindowState.Minimized)
this.Invalidate(true);
}
catch (System.ArgumentException ax)
{
World.Debugging.RTMessage("FindNextCritter()", "System.ArgumentException", "Exception: " + ax);
}
catch (Exception ex)
{
World.Debugging.RTMessage("FindNextCritter()", "this.Invalidate()", "Exception: " + ex);
}
try
{
if (WindowState != FormWindowState.Minimized)
this.Update();
}
catch (System.ArgumentException ax)
{
World.Debugging.RTMessage("FindNextCritter()", "System.ArgumentException", "Exception: " + ax);
}
catch (Exception ex)
{
World.Debugging.RTMessage("FindNextCritter()", "this.Update()", "Exception: " + ex);
}
... more stuff
}
The debugger pointed to the line that says "this.Update()", but neither of the two catch blocks on the associated Try managed to catch the exception. Remember, I also get the same result when I turn off the monitor or drag the form off the screen, but then the unhandled exception points to my Application.DoEvents() statement, which is also wrapped in a try block that fails to catch the exception. The rather wordy test code above is an attempt to isolate the issue.
I am using Microsoft Visual C# 2010 Express; you know, the free SDK downloaded from Microsoft. I suspect that I have done something stupid to the form, but I don't think I can upload that to show it. It contains 8 bitmap images that the program successfully updates from bitmap objects built internally, one doughnut graph defined on the form, two buttons, four radio buttons in a groupbox, several labels and textboxes, a checkbox, and another groupbox enclosing two of the bitmaps, the doughnut graph, and a label. Some of the labels have \n in them and stretch across multiple lines.
Yes, I know this is a big form. It's currently running on a TV screen with a form size of 1831,977. It was just more convenient and informative to have everything up there at once.
Thanks in advance for your help. I have googled around and found people with similar issues, but with no relevant solution. I am not an experience C# coder (old school CICS/COBOL here!) and I do not have local peers to ask.
|
|
|
|
|
Well, if you're using Application.DoEvents, you're doing something very wrong. Even more so with repainting individual controls or images. DoEvents doesn't go back to your apps normal message pump to process any pending messages, like WM_PAINT. It processes them in place, in it's own loop until the message queue is empty, essentially putting your app "on hold".
DON'T USE THIS, EVER. It just causes problems, like what you're dealing with.
|
|
|
|
|