簡體   English   中英

如何動態增加Datagridview的行並立即獲得組合框的值?

[英]How to increase rows of Datagridview dynamically and get the combobox values all at once?

我在這里看到了許多與此有關的問題,但對我來說,這些問題都沒有。 所以任何可以在這里幫助我的人。 首先,我從亞馬遜網站上抓取數據並將數據保存在此DataGridView中

dataGridViewScraping數據:

在此處輸入圖片說明

dataGridViewASINs:

在此處輸入圖片說明

我成功地抓取了第一頁數據,但是當我嘗試抓取第二個數據並嘗試將數據放入datagridview時,出現錯誤

索引超出范圍。 必須為非負且**

當循環第二次返回並且我放入DataGridView的第一個數據是title時,我在這里也遇到錯誤:

 for (int i = 0; i < dataGridViewASINs.Rows.Count - 1; i++)
    {
 //Getting Title
            string title = driver.FindElement(By.Id("productTitle")).GetAttribute("innerText");
            dataGridViewScrapingData.Rows[i].Cells[cols].Value = title;
}

我正在使用此代碼將數據放入datagridview中的所有其他列代碼類似於我正在使用的代碼

行[指數] .Cells [索引]

對於所有列,但對於組合框列,我認為我沒有使用此索引,因此也僅適用於第一次迭代

 for (int i = 0; i < dataGridViewASINs.Rows.Count - 1; i++)
        {
 List<IWebElement> imageCounts = driver.FindElements(By.XPath("//ul[@class='a-unordered-list a-nostyle a-button-list a-vertical a-spacing-top-extra-large']//li[@class='a-spacing-small item imageThumbnail a-declarative']//span[@class='a-button-text']//img")).ToList();        
                element = driver.FindElement(By.Id("landingImage"));
                comboState.Items.Add(element.GetAttribute("src"));        
                for (int j = 0; j < imageCounts.Count - 1; j++)
                {
                    //Clicking that Element
                    string GenricXpath = "//ul[@class='a-unordered-list a-nostyle a-button-list a-vertical a-spacing-top-extra-large']//li[" + (j + 5).ToString() + "]//span[1]//span[1]//span[1]//input[1]";
                    element = driver.FindElement(By.XPath(GenricXpath)); element.Click();
                    //Extracting URL now
                    string AnotherXpath = "//li[@class='image item itemNo" + (j + 1).ToString() + " maintain-height selected']//img";
                    element = driver.FindElement(By.XPath(AnotherXpath)); comboState.Items.Add(element.GetAttribute("src"));
                }
                dataGridViewScrapingData.Columns.Add(comboState);
}

除此之外,我還想將數據放入datagridviewScrapingData之后。 我不知道如何獲取DataGridViewScraping數據的combobox列中的全部數據。 我想將數據從datagridviewScrapingData獲取到字符串列表中,在此我已保存了全部數據。 我在stackoverflow上也看到了許多與此相關的問題,但是對我來說,這些問題都沒有任何意義。

看來您使用dataGridView的方法有點不正確。 您嘗試直接使用數據網格行,但其想法是擁有一個單獨的集合,如List<Product>並通過綁定源顯示它。

1.首先創建一個代表您的產品的類,例如:

public class Product
{
    public string Title { get; set; }
    public string Asin { get; set; }
}

2.創建一個產品列表並將其刮到該列表。

3.在表單設計器中單擊dataGridView,然后注意右上角的箭頭按鈕。 單擊它,然后通過選擇您的Product類來生成新的數據源。 DataGridBindingSource將出現在表單設計器的底部。 假設它的名稱是dataGridViewBindingSource

4.將您的產品集合分配給綁定源:

dataGridViewBindingSource.DataSource = products;

現在,您可以通過調用dataGridView.Refresh()方法來修改產品集合並在網格中顯示更新的產品。 此時,您應該擺脫“索引超出范圍”異常,並且可以引用產品集合,因此不必從數據網格行中顯式“提取”它們。

5.無需從ComboBox中獲取值,您可以先將選項存儲在產品中,然后將其添加到組合框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM