|
Yes, except it still does not work. And if you get of range errors you need to diagnose the problem and fix your code rather than just ignoring it.
|
|
|
|
|
Richard,
Coming to this site doesn't mean that I was ignoring the problem, one cannot complete a task if they ignore the problems. Me coming to this site was me asking for help for an issue that I've been trying to fix for some time. I kindly ask, if you cannot help with the issue please don't reply again.
Thank you
|
|
|
|
|
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.
|
|
|
|
|