简体   繁体   English

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

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

The problem I am facing seems simple to me, but I cannot push past this mental block. 我面临的问题对我来说似乎很简单,但我不能超越这个心理障碍。

To explain my situation a little better: I am reading in values from an mdf database (Northwind) and passing the ContactName column into a class method that splits the value into first and last names. 为了更好地解释我的情况:我正在读取mdf数据库(Northwind)中的值并将ContactName列传递给一个类方法,该方法将值拆分为名字和姓氏。 It then passes these back and I attempt to add them to my DataGridView under the proper columns I created. 然后它传回这些,我尝试将它们添加到我创建的正确列下的DataGridView中。

My problem is, is that with this current code, it is adding rows for each column, but they are all blank aside from the last one, which shows the last first and last name in the tables column. 我的问题是,对于这个当前代码,它是为每列添加行,但除了最后一个列之外它们都是空白的,它显示了表列中的最后一个和最后一个名称。

I feel that for some reason, the rows that are showing blank might be being overwritten, but I'm not sure. 我觉得由于某种原因,显示空白的行可能会被覆盖,但我不确定。 Am I on the right track? 我是在正确的轨道上吗?

Here is my code: 这是我的代码:

            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;
            }

While that seems like a mouthful to me, I hope I explained it clearly enough. 虽然这对我来说似乎是满口的,但我希望我能够清楚地解释清楚。 If you need more information, please let me know and I would be more than happy to provide it. 如果您需要更多信息,请告诉我,我非常乐意提供。 Thank you :) 谢谢 :)

You aren't updating the rowIndex variable as you add rows. 在添加行时,不会更新rowIndex变量。 This line needs fixing: 这条线需要修理:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM