用一个默认的空行填充DataGridView

3

我正在开发一个Windows应用程序(C#)。我有一个DataGridView,我能够绑定数据并显示数据,一切都很好。但是我希望我的DataGridView在没有数据可显示时也能显示一个默认的空行。目前,当没有数据可用时,DataGridView是空的。谢谢!


2
在绑定的数据表中添加一个空白行。 - thewisegod
是的,它起作用了。非常感谢你!! - Reed
1个回答

2
当您使用数据绑定来绑定DataGridView到一个BindingSource时,属性AllowUserToAddRows的值为true,DataGridView总是在底部有一条空记录,以便您添加新记录。
您不需要使用其他方式在绑定的DataGridView底部添加空记录。
以下是一个创建数据列表表单的简单示例:
  1. 创建一个表单并在其中放置DataGridViewBindingNavigatorBindingSoure
  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;

截图:

看看那个数据网格视图底部的空记录。

在此输入图片描述


嗨 Reza,非常感谢您的回复!! "AllowUserToAddRows" 已经设置为 true,但即使如此空白行也从未显示。但现在,根据 "thewisegod" 的解决方案,我所做的是 - DataRow newrow = dt.NewRow(); dt.Rows.Add(newrow); 然后它起作用了。不确定为什么 AllowUserToAddRows 没有发挥作用。 - Reed
Reza,我试过了,它确实像你说的那样做,只要我开始在那一行的某一列中输入,新行就会显示在底部。出于某种原因,在我的情况下没有发生。不确定我哪里错了。我需要再仔细检查一下。另外,有什么快速的想法吗?如何使网格视图中的列在单击列标题时可排序? - Reed
干得好!当使用datatable作为数据源时,默认情况下列是可排序的。但是,如果您使用List<T>作为数据源,请考虑改用SortableBindingList<T> - Reza Aghaei
我曾经设置了AllowUserToAddRows=true,但是却得到了一个神秘的(在我的情况下不希望出现的)空行。你的答案指出了罪魁祸首 - 谢谢! - Valid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接