【问题标题】:DataGridView generating rows without dataDataGridView 生成没有数据的行
【发布时间】:2016-12-02 21:40:55
【问题描述】:

我已经在这里和谷歌搜索过,但仍然找不到答案。我正在使用 Amazon 的 API,并且正在制作一个简单的 Windows 窗体来尝试在 DataGridView 中显示数据。 GridView 为我得到的 10 个结果生成 10 行,但没有用实际数据填充这些行。它们只是空白。

下面的代码是一个返回 DataTable 的方法 (GetResults)。我没有全部展示,因为上面有一堆代码来获取数据。

            DataTable dt = new DataTable();
            dt.Columns.Add("ASIN", typeof(string));
            dt.Columns.Add("Title", typeof(string));

            // write out the results
            foreach (var item in response.Items[0].Item)
            {
                Product product = new Product(item.ASIN, item.ItemAttributes.Title);
                Console.WriteLine(product.ASIN);
                var dr = dt.NewRow();
                dr["ASIN"] = product.ASIN;
                dr["Title"] = product.Title;
                dt.Rows.Add();
            }
            return dt;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            dgvProducts.AutoGenerateColumns = false;
            dgvProducts.DataSource = GetReults();
        }

我知道它正在获取信息,因为我正在将它写入控制台并且它显示正确。

我也有这个产品的基本类:

public class Product
    {
        private string asin;
        private string title;

        public Product() { }

        public Product(string newAsin, string newTitle)
        {
            this.asin = newAsin;
            this.title = newTitle;
        }


        public string ASIN
        {
            get { return asin; }
            set { asin = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

我尝试设置 AutoGenerateColumns = false 并自己设置列数据绑定,但这也没有任何作用。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您正在向表中添加一个空行,而不是添加新创建的行。

    Change
         dt.Rows.Add();
    To
         dt.Rows.Add(dr);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多