【问题标题】:How to add row in DataGridView programmatically如何以编程方式在 DataGridView 中添加行
【发布时间】:2013-05-15 03:13:16
【问题描述】:

我在这里尝试过这段代码。但是,我现在的问题是,它没有显示任何数据。

这是我的代码

try
{
    DataTable dt = new DataTable();
    con.Open();

    dt.Load(new MySqlCommand("SELECT variant_name FROM tblVariant_Product WHERE product_name='" + cboProduct.Text + "'", con).ExecuteReader());

    DataColumn col = dt.Columns.Add(new DataColumn("Quantity", typeof(Int32));
    col.AllowDBNull = false;

    DataRow row = dt.NewRow();
    row["variant_name"] = "TOTAL";
    row["quantity"] = 0;
    dt.Rows.Add(row);

    dataGridView2.DataSource = dt;
    con.Close();
}
catch (Exception)
{
}

【问题讨论】:

  • dataGridView2.DataBind() ?
  • @DevProve 在键入 datagridview2 和数据绑定的时间段后不会显示在智能感知中,而是显示 DataBindings 和 DataBindingComplete。
  • @DevProve 还有另一种添加新行的方法吗?
  • 抱歉,你的是窗口应用

标签: c# winforms datagridview add rows


【解决方案1】:

写:

dt.AcceptChanges(); 

之后:

dt.Rows.Add(row);

【讨论】:

  • 同样,我在我的数据库表tblVariant_Product 中再次检查它有数据,但是当我运行程序时它不显示该数据。这是为什么呢?
  • 请在此 dt.Load(new MySqlCommand("SELECT variant_name FROM tblVariant_Product WHERE product_name='" + cboProduct.Text + "'", con).ExecuteReader()) 处检查 dt在调试时 datatable(dt) 是否包含此时的数据?
  • 对不起,我是 Visual Studio 的初学者,我怎么知道 dt 包含数据?
  • 在此行使用 F9 键添加调试点并运行应用程序
  • 好的,我已经在运行该应用程序,并且该行突出显示,光标闪烁,然后?
【解决方案2】:

添加列:

dt.Columns.Add(new DataColumn("ColumnName",Type.GetType("System.String")));

最好先删除它:

dataGridView2.DataSource = dt;

【讨论】:

  • 不,它有两列 variant_nameQuantity,而 Quantity 是我在 datagridview2 属性中添加的。
  • 好的,我明白了...我想我知道错误所在。所以现在我有一个问题,如果你不介意的话,在数据表中添加列的语法是什么?
  • 它没有显示任何数据,反正我已经更新了我的问题。
  • 检查你的 cboProduct.Text 它可能为空
  • 我不这么认为,因为它以前可以正常工作。
【解决方案3】:
try{
    DataTable dt = new DataTable();
    con.Open();

    dt.Load(new MySqlCommand("SELECT variant_name FROM tblVariant_Product WHERE product_name='" + cboProduct.Text + "'", con).ExecuteReader());

    dt.Columns.Add(new DataColumn("Quantity", typeof(Int32));

    DataRow row = dt.NewRow();
    row["variant_name"] = "TOTAL";
    row["quantity"] = 0;
    dt.Rows.Add(row);

    dataGridView2.DataSource = dt;
    con.Close();
 }
 catch (Exception)
 {
 }

【讨论】:

    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    相关资源
    最近更新 更多