[ad_1]
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?
我尝试过的:
我尝试了以下代码。
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; } }
解决方案1
根据您的代码片段,有几个问题可能会导致意外行为。 你正在创建一个 DataTable
在循环内,导致它在每次迭代时重置。 要解决此问题,请移动 DataTable
在循环外创建并设置 DataTable
作为 DataSource
循环之后。 以下是您的代码的更新版本:
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;
[ad_2]
コメント