Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to pull all the items in the drop-down menu one by one into the datagridview rows using Selenium in C#. Can you help me on this issue?


What I have tried:

I tried the following codes.
I tried the code below, but these codes pull all elements into one line.

<pre lang="C#">
List<IWebElement> selectElements = drv.FindElements(By.Id("dersler"));
foreach (IWebElement select in selectElements)
{
    var selectElement = new SelectElement(select);
    List<string> lst = new List<string>();
    lst.Add(select.Text);
    DataTable dt = new DataTable();
    DataColumn dtcol = new DataColumn(select.Text);
    dt.Columns.Add(dtcol);
    for (int i = 0; i < lst.Count; i++)
    {
       dataGridView1.DataSource = dt;
    }

}
Posted
Comments
Graeme_Grant 17-Jan-24 17:58pm    
Without seeing the html markup that you are tyring to parse, we cannot comment on the code. Remember, we can not see your screen.

1 solution

As per your code snippet, there are a couple of issues that might be leading to the unexpected behavior. You're creating a DataTable within the loop, causing it to reset with each iteration. To address this, move the DataTable creation outside the loop and set the DataTable as the DataSource after the loop. Below is the updated version of your code:
C#
List<IWebElement> selectElements = drv.FindElements(By.Id("dersler"));
// Create DataTable outside the loop to avoid resetting it in each iteration
DataTable dt = new DataTable();
foreach (IWebElement select in selectElements)
{
    var selectElement = new SelectElement(select);

    // Create a new column for each dropdown
    DataColumn dtcol = new DataColumn(selectElement.Text);
    dt.Columns.Add(dtcol);

    // Create a new row for each option in the dropdown
    foreach (IWebElement option in selectElement.Options)
    {
        DataRow row = dt.NewRow();
        row[selectElement.Text] = option.Text;
        dt.Rows.Add(row);
    }
}
// Set the DataTable as the DataSource after the loop
dataGridView1.DataSource = dt;
 
Share this answer
 
Comments
Member 12505620 18-Jan-24 11:51am    
Thanks for your intrest, M. imran Ansari. It pulls data twice with these codes. In the first line, it draws all the courses at the same time. The next lines work correctly. If we destroy all the classes in the first row, there will be no problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900