C# checkedListBox Open Excel file when it´s only one

Hi,

I want to “open/Load” an Excel file and read specific cells out of it and display them in textboxes in my Windows Form.

So far so easy, but I’m not sure how I can open an Excel file that was selected by a “checkedListBox”.
Here is the code I have so far.

var sourceFileNames5 = checkedListBox5.Items.Cast<String>().ToArray();

var files5 = Directory.GetFiles(@"C:\ProgramData\UpdateReports\02_Comments\", "*.xlsx");
checkedListBox5.Items.AddRange(files5);

ExcelFile workbook = ExcelFile.Load(files5);
ExcelWorksheet worksheet = workbook.Worksheets[0];
ExcelCell cell = worksheet.Cells[9, 4];
Console.WriteLine(cell.Value);

Could you help me on how to get the path of the selected Item and place it in “Load(files5)”
As well as how to write the Value of the cell in to textBox.Text.

P.S. it is only one Item selectable in my “checkedListBox”.

Hi Andreas,

Try using this:

string file = checkedListBox1.CheckedItems[0];
ExcelFile workbook = ExcelFile.Load(file);
ExcelWorksheet worksheet = workbook.Worksheets[0];
ExcelCell cell = worksheet.Cells[9, 4];
textBox.Text = cell.Value.ToString();

Regards,
Mario

Hi Mario,

sadly this does not work, i somehow can not write a checkedListBox.checked Item to a string.

also the textBox.Text = cell.Value.ToString() does not work.

Regards,
andreas

Hi Andreas,

Please send us your Visual Studio project so that we can investigate it.
I’m afraid I’ll need to debug your solution in order to troubleshoot the problem.

Regards,
Mario

I Mario,

i solved now the problem of Loading the file, by:

var all = string.Join(Environment.NewLine, selectedItems.Select(x => x.Path));
MessageBox.Show(all);

and a public class, foreach, … etc.

but still i can´t write textBox.Text = cell.Value.ToString();

maybe because cell.Value is an Object and not a String"Value"?

The cell.Value is an object because it can be a String, Double, Integer, DateTime, or null.
But calling the ToString() on it should give you a String value.