I want to fetch data from tables in UI. I know about looping through rows and columns using \"tr\" and \"td\". But the one the table I have is something like this:
The below code you can not only get the rows and columns of the table but also you can get the order in which they are in the Browser,this is mainly handy if you have a nested structures in the TD column as in your case.
public DataTable StoreHtmlTableToDataTable(IWebElement tblObj,bool isFirstRowHeader = true)
{
DataTable dataTbl = new DataTable();
int rowIndex = 0;
try
{
//_tblDataCollection = new List();
var tblRows = ((IJavaScriptExecutor)DriverContext.Driver).ExecuteScript("return arguments[0].rows; ", tblObj);
if (tblRows != null)
{
//Iterate through each row of the table
foreach (IWebElement tr in (IEnumerable)tblRows)
{
int colIndx = 0;
DataRow dtRow = dataTbl.NewRow();
// Iterate through each cell of the table row
var tblCols = ((IJavaScriptExecutor)DriverContext.Driver).ExecuteScript("return arguments[0].cells; ", tr);
foreach (IWebElement td in (IEnumerable)tblCols)
{
//add the header row of the table as the datatable column hader row
if (rowIndex == 0)
{
dataTbl.Columns.Add("Col" + colIndx.ToString(), typeof(string));
}
dtRow["Col"+colIndx.ToString()] = td.Text;
//loop through any child or nested table structures if you want using the same approach for example links,radio buttons etc inside the cell
//Write Table to List : This part is not done yet
colIndx++;
}
dataTbl.Rows.Add(dtRow);
rowIndex++;
}
}
}
catch (Exception)
{
throw;
}
//if first row is the header row then assign it as a header of the datatable
if (isFirstRowHeader)
{
dataTbl = this.AssignDataTableHeader(dataTbl);
}
return dataTbl;
}