I have a problem with messagebox.
Form1:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
Class1 excel = new Class1(dialog.FileName, 1);
string path = dialog.FileName + ".txt";
TextWriter tw = new StreamWriter(path, true);
tw.Write(excel.ReadCell(0, 0));
tw.Close();
}
}
}
}
Class1:
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
class Class1
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
private object excelWorksheet;
public Class1(string path, int Sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = (Worksheet)wb.Worksheets[Sheet];
}
public string ReadCell(int row, int column)
{
column += 1;
do
{
row++;
if(((_Excel.Range)ws.Cells[row, column]).Value2 == null)
break;
_Excel.Range range = (_Excel.Range)ws.Cells[row, column];
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
else
{
MessageBox.Show("Hodnota nenalezena!");
}
} while (true);
return "";
}
}
}
When I write the code like this, the messagebox always appears. But I would need him to show up only if the value is not in the excel file.
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
else
{
MessageBox.Show("Hodnota nenalezena!");
}
The problem is this checks the first cell, finds that the value is not found and writes a messagebox. So I know where the problem is and why the problem is, but I don't know how to combine it to make it work.
Thank you all for the advice.
If I understand correctly;
You're returning if you find the value already, so instead of giving same message when every column is read in the "else" section.
It will be correct to give a message when you cannot find all the data except do{}while(true).
Like this;
public string ReadCell(int row, int column)
{
column += 1;
do
{
row++;
if(((_Excel.Range)ws.Cells[row, column]).Value2 == null)
break;
_Excel.Range range = (_Excel.Range)ws.Cells[row, column];
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
} while (true);
MessageBox.Show("Hodnota nenalezena!");
return "";
}