簡體   English   中英

向datagridview添加行時,除最后一行外不會插入任何值

[英]While adding rows to datagridview, no values are inserted except last row

我面臨的問題對我來說似乎很簡單,但我不能超越這個心理障礙。

為了更好地解釋我的情況:我正在讀取mdf數據庫(Northwind)中的值並將ContactName列傳遞給一個類方法,該方法將值拆分為名字和姓氏。 然后它傳回這些,我嘗試將它們添加到我創建的正確列下的DataGridView中。

我的問題是,對於這個當前代碼,它是為每列添加行,但除了最后一個列之外它們都是空白的,它顯示了表列中的最后一個和最后一個名稱。

我覺得由於某種原因,顯示空白的行可能會被覆蓋,但我不確定。 我是在正確的軌道上嗎?

這是我的代碼:

            conn.Open();

        SqlDataReader reader = command.ExecuteReader();

        searchDataGridView.AllowUserToAddRows = true;

        Customer cust = new Customer();

        searchDataGridView.ColumnCount = 2;
        searchDataGridView.Columns[0].Name = "First Name";
        searchDataGridView.Columns[1].Name = "Last Name";

        int index = this.searchDataGridView.Rows.Count;

            while (reader.Read())
            {

                string customerid = reader.GetString(0);
                string contactname = reader.GetString(2);

                cust.NameSplit(contactname);

                this.searchDataGridView.Rows.Add();

                DataGridViewRow r = searchDataGridView.Rows[rowIndex];

                r.Cells["First Name"].Value = cust.FirstName;
                r.Cells["Last Name"].Value = cust.LastName;
            }

雖然這對我來說似乎是滿口的,但我希望我能夠清楚地解釋清楚。 如果您需要更多信息,請告訴我,我非常樂意提供。 謝謝 :)

在添加行時,不會更新rowIndex變量。 這條線需要修理:

rowIndex = this.searchDataGridView.Rows.Add();

暫無
暫無

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

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