【问题标题】:Add Column and Rows in DataGridView c#在 DataGridView c# 中添加列和行
【发布时间】:2021-04-22 21:15:13
【问题描述】:

我实际上有一个加载了 sql 查询的 datagridview。我想在不清除所有数据的情况下添加一个包含一些行的新列。

我将在行中插入的值是列表中的字符串。这个列表是由已经加载的datagridview的第一列的sql查询加载的。

所以我基本上想做:

Seals_DataGridView.Columns.Add("column_Type", "Title Column");

        Seals_DataGridView.Rows.Add("GOGO"); 

但显然这个不行

有人有帮助我的想法吗?

谢谢

【问题讨论】:

  • 有什么不好的?我想你只想遍历行并为新列设置值
  • 我已经看过这篇文章,老实说,我对 DataSource 方面不是很友好,这就是我对我的 datagridview 使用 SQL 查询的原因。我真的不明白如何解决我的问题。目标是添加一个新列,是的,之后我将遍历行。添加列而不清理我的数据这是我的主要问题

标签: c# sql winforms


【解决方案1】:

如果您想从代码中添加行,请尝试使用 DataTable 和 DataGridViewDataSource

string constring = @"Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass@123";
        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
            {
                cmd.CommandType = CommandType.Text;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        dataGridView1.DataSource = dt;
                    }
                }
            }

其他最好的方法是使用 Grapically

解决您的问题

Seals_DataGridView.Columns.Add("column_Type", "Title Column");
        Seals_DataGridView.Rows.Add("GOGO"); 

您提供的代码对我来说非常有效,我不知道您的代码有什么问题需要详细说明

【讨论】:

  • 感谢您的回答,如果我通过datagridview的属性添加新列,这个不会删除我的数据源加载的数据?
  • 错误是:“当控件是数据绑定时,无法将行编程添加到 DataGridView 行集合”。但我可以看到错误背后的新列
  • 我发现您的回答存在问题,但主要问题已通过您的建议得到解决,谢谢
  • 非常欢迎您解决问题
猜你喜欢
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多