【问题标题】:Populate DataGridView with a default empty row使用默认空行填充 DataGridView
【发布时间】:2015-11-27 01:26:10
【问题描述】:

我正在开发一个 Windows 应用程序 (c#)。我有一个DataGridView,我可以绑定数据并显示数据,一切都很好。但我希望我的DataGridView 显示一个默认的空行,即使数据库没有要显示的数据。现在,当没有可用数据时,DataGridView 为空。提前谢谢!

【问题讨论】:

  • 在您绑定的数据表中添加一个空白行。
  • 是的,它奏效了。非常感谢!!

标签: c# .net winforms data-binding datagridview


【解决方案1】:

当您对DataGridView 使用数据绑定并将其绑定到BindingSource 时,属性AllowUserToAddRows 的值为true,DataGridView 底部始终有一个空记录,以便您添加新记录。

您永远不需要使用其他方式在绑定的 DataGridView 底部添加空记录。

这是一个创建数据列表表单的小示例:

  1. 创建一个表单并在其上放置一个 DataGridView、一个 BindingNavigator 和一个 BindingSoure
  2. 双击您的表单并将下面的代码写入 Form_Load 事件:

代码:

//example: @".\sqlexpress;initial catalog=YourDatabase;integrated security=True;"
var connection = @"Your Connection String" ;
//example: "SELECT * FROM Category"
var command = "Your Command";
var tableAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable= new DataTable();
//Get data
tableAdapter.Fill(dataTable);
//Set databindings
this.bindingSource1.DataSource = dataTable;
this.dataGridView1.DataSource = this.bindingSource1;
this.bindingNavigator1.BindingSource = this.bindingSource1;

截图:

查看 datagridview 底部的空记录。

【讨论】:

  • 嗨 Reza,非常感谢您的回复! “AllowUserToAddRows”已经设置为 true,即使这样,空白行也从未显示。但是现在,我基于“thewisegod”解决方案所做的是 - DataRow newrow = dt.NewRow(); dt.Rows.Add(newrow);它奏效了。不知道为什么 AllowUserToAddRows 不起作用。
  • Reza,我确实尝试过,它完全按照你说的做,只要我开始输入该行中的一列,新行就会显示在底部。出于某种原因,在我的情况下没有发生。不知道我哪里出错了。我需要仔细检查。另外,任何快速的想法,如何在单击列标题时使列在网格视图中排序?
  • 干得好!使用数据表作为数据源时,列可按默认排序。但如果您使用 List 作为数据源,请考虑改用 SortableBindingList<T>
  • 我有 AllowUserToAddRows=true 并且得到了一个神秘的(在我的情况下是不受欢迎的)空白行。您的回答指出了罪魁祸首-谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 2021-01-04
相关资源
最近更新 更多