数据表上的行标题 - 显示在 datagridview 中
无论如何,是否可以将行标题信息存储在数据表中,以便当我将其绑定到 datagridview 时,它将自动显示 C# 中的列标题和行标题?
Is there anyway to store row header information in a datatable so that when i bind it to a datagridview, it will automatically display both the column and row headers in c#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Linqpad 演示程序
据我了解,您希望将列名称作为值添加到数据表/数据网格视图。以下是 Linqpad - 程序,您可以轻松地将其复制粘贴到 Linqpad 中进行使用。该代码将列名称添加到数据表的第一行。您可以轻松地将此数据表绑定到 gridview - 但请注意数据表的每一列都必须是字符串类型。
更新 2019-06,包含附加说明和替代代码
方法
GetHeaders
不是获取标题的最简单选项。以前,扩展方法
Cast(IEnumerable)
用于 DataColumnCollection-Class 另一种方法是迭代集合 - 这就是在GetHeadersNew
T这可能更有效,因为涉及的对象和方法更少。
Linqpad Demo-Program
As far as i understood you would like to add the column name as values into the datatable / the datagridview. The following is a Linqpad-Program you can easily copy paste into Linqpad to play around. The code adds the column-names to the first row to the datatable. You can easily bind this datatable to a gridview - but beware that each column of the datatable must be of type string.
Update 2019-06 with additional explanation and alternative code
The method
GetHeaders
is not the simplest option to get the headers.Previoulsy the extension method
Cast<TResult>(IEnumerable)
was used on the DataColumnCollection-Class An alternative would be to just iterate over the collection - this what is done InGetHeadersNew
TThis is likely more efficient because less objects and methods are involved.
只要您可以使用基于行中数据的代码创建它们,我就可以使用 c# 在运行时添加它们。将一列添加到数据表并使用 foreach 循环遍历它。只要行数不是太多,此代码就会执行得非常快:
然后输出新列 rowheader 作为网格中的第一个单元格。
另一种解决方案是使用 sql 查询在结果集中返回“额外”列。例如:
通过这种方式,您可以让 SQL 完成所有工作。
As long as you can create them with the code based on the data in the row I would just add them at run time using c#. Add a column to the datatable and run through it with a foreach loop. As long as there are not too many rows this code will execute very quickly:
Then output the new column rowheader as the first cell in the grid.
Another solution is to use the sql query to return an 'extra' column in the result set. for example:
In this way you make SQL do all the work.