Search code examples
c#.netdatasetexceldatareader

How can I get specific info from exception to add it in my own message?


I am retrieving data from a xlx/xlxs file. I'm actually using ExcelDataReader library to save the data into a DataSet using ExcelDataReader plugin.

excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
excelDataTable = excelReader.AsDataSet(conf);

Now I am trying to convert System.Data.DataSet into a strongly typed dataset.

public DocAdmin.GHDefinitionDataTable ConvertDataTable(DataTable dtOriginal)
    {

        DocAdmin.GHDefinitionDataTable ghDefiniton = new DocAdmin.GHDefinitionDataTable();
        int ExcelRowNumber = 1;
        foreach (DataRow row in dtOriginal.Rows)
        {
            ++ExcelRowNumber;
            try
            {
                ghDefinition.ImportRow(row);
            }
            catch (ArgumentException ex)
            {
                OperationMessage message = new OperationMessage();
                this.ShowMessage(message );
            }

        }
        return ghDefinition;
    }

I'm getting this exception message:

Input string was not in a correct format.Couldn't store in SAHasta Column. Expected type is Decimal.

This is because I'm setting "NULL" values on a cell on purpose.

I would like to show a message specifying the row number (cell number on Excel file), I'm using the ++ExcelRowNumber to show this, but I don't know how to get the column name and data type from the strongly typed dataset which is giving me the exception. I know the exception specify this for itself: Couldn't store in SAHasta Column, but I have to do a custom message in Spanish.

I'm wondering if there is a way to get the column name and the data type from the exception. I would like to specify to the user the value giving the problem so he can modify the excel file and upload it again.

Thanks in advance and sorry for my English.


Solution

  • What about something as simple as this to get the failing row?

    public DocAdmin.GHDefinitionDataTable ConvertDataTable(DataTable dtOriginal)
    {
    
        DocAdmin.GHDefinitionDataTable ghDefiniton = new DocAdmin.GHDefinitionDataTable();
        int ExcelRowNumber = 1;
        foreach (DataRow row in dtOriginal.Rows)
        {
            ++ExcelRowNumber;
            try
            {
                ghDefinition.ImportRow(row);
            }
            catch (ArgumentException ex)
            {
              System.Windows.Forms.MessageBox.Show("Error on line " + ExcelRowNumber)
            }
    
        }
        return ghDefinition;
    }
    

    To get to know the exact value the Import module fails at, you will need to look at the DocAdmin.GHDefinitionDataTable definition itself. It is hard to tell without knowing how that bit works.