TransWikia.com

How can I solve OutOfRangeException on using Selenium C#

Software Quality Assurance & Testing Asked by Ugochukwu Anajemba on January 9, 2021

I was faced with the below problem while trying to run a data driving testing and have tried to resolve it but nothing seem to be working for me. Please could you take a look at my code and tell me where i went wrong and what to do in order to correct it. thank you.

[Test]
    public void ExecuteTest()
    {
        //Import from excel
        ExcelLib.PopulateInCollection(@"C:UsersCUBADesktopBook1.xlsx");
        //Login to app
        EALoginPage loginPage = new EALoginPage();
        EAFormPage formPage = loginPage.Login(ExcelLib.ReadData(1, "UserName"), ExcelLib.ReadData(1, "Password"));
        PropertiesCollection.Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
        formPage.FillUserForm(ExcelLib.ReadData(1, "Initial"), ExcelLib.ReadData(1, "MiddleName"), ExcelLib.ReadData(1, "FirstName"));

    }

Below is my excelLib.cs class

    private static DataTable ExcelToDataTable(string fileName)
    {
        //open file and returns as Stream
        FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
        //Createopenxmlreader via ExcelReaderFactory
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx

        // excelReader.IsFirstRowAsColumnNames = true;
        var result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
        {
            ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
            {
                UseHeaderRow = true
            }
        });
        //Return as DataSet
        //DataSet result = excelReader.AsDataSet();
        //Get all the Tables
        DataTableCollection table = result.Tables;
        //Store it in DataTable
        DataTable resultTable = table["Sheet1"];

        //return
        return resultTable;
    }



       static List<Datacollection> dataCol = new List<Datacollection>();

    public static void PopulateInCollection(string fileName)
    {
        DataTable table = ExcelToDataTable(fileName);

        //Iterate through the rows and columns of the Table
        for (int row = 1; row <= table.Rows.Count; row++)
        {
            for (int col = 0; col <= table.Columns.Count; col++)
            {
                Datacollection dtTable = new Datacollection()
                {
                    rowNumber = row,
                    colName = table.Columns[col].ColumnName,
                    colValue = table.Rows[row - 1][col].ToString()
                };
                //Add all the details for each row
                dataCol.Add(dtTable);
            }
        }
    }


       public static string ReadData(int rowNumber, string columnName)
    {
        try
        {
            //Retriving Data using LINQ to reduce much of iterations
            string data = (from colData in dataCol
                           where colData.colName == columnName && colData.rowNumber == rowNumber
                           select colData.colValue).SingleOrDefault();

            //var datas = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue;
            return data.ToString();
        }
        catch (Exception e)
        {
            return null;
        }
    }
}


       public class Datacollection
    {
        public int rowNumber { get; set; }
        public string colName { get; set; }
        public string colValue { get; set; }
    }

}

Any help will be appreciated. Thanks.

One Answer

Your issue seems to be here

 for (int row = 1; row <= table.Rows.Count; row++)
        {
            for (int col = 0; col <= table.Columns.Count; col++)
            {
                Datacollection dtTable = new Datacollection()
                {
                    rowNumber = row,
                    colName = table.Columns[col].ColumnName,
                    colValue = table.Rows[row - 1][col].ToString()
                };
                //Add all the details for each row
                dataCol.Add(dtTable);
            }
        }

You should carefully check the indices because for example this loop

for (int col = 0; col <= table.Columns.Count; col++)

will be executed one time more than your column count. Assume you have 2 columns in a table. Your loop start from 0, then 1 then finally 2 (because 2 <= 2) which will compose totally 3 loop cycles. I believe you will get out-of-range exception here.

Read more about fetching rows here. Below is the example from MSDN doc from the latter link:

private void PrintRows(DataTable table)
{
    // Print the CompanyName column for every row using the index.
    for(int i = 0; i < table.Rows.Count; i++)
    {
        Console.WriteLine(table.Rows[i]["CompanyName"]);
    }
}

Answered by Alexey R. on January 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP