简体   繁体   English

如何使SQL表中特定列的值作为GridView的标题

[英]How to make values of a particular column in SQL table as headers of GridView

在此处输入图片说明

I have SQL database table as shown in the image. 我有SQL数据库表,如图所示。 I want values of column Location_Instance (ie, the second column in the image) to to displayed as headers of a GridView . 我希望将Location_Instance列(即图像中的第二列)的值显示为GridView标题。 Right now I am copying the column the to a ListBox and using the ListBox to be displayed as headers. 现在,我将列复制到ListBox并使用ListBox作为标题显示。 But I want to display directly from datasource. 但是我想直接从数据源显示。 Can anyone kindly help me on this. 任何人都可以在这方面帮助我。 Thank you in advance. 先感谢您。

One way to do this would be to write some additional code that creates a new DataTable with the columns set how you want, then insert rows how you want to, from the data in the database. 一种实现方法是编写一些额外的代码,以创建新的DataTable,并使用所需的列设置新的DataTable,然后根据数据库中的数据插入所需的行。

Doing it in SQL is difficult. 在SQL中很难做到这一点。

See http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx for how to do this ... 有关如何执行此操作,请参阅http://msdn.microsoft.com/zh-cn/library/hfx3s9wd.aspx

您不能直接将列的值设置为网格视图中的标题,首先必须将其保存在某个位置,例如ViewState或任何控件

Write a Select Query and Get the data 编写一个选择查询并获取数据

like 喜欢

Select * from Tbl where 'Condition'

Fill the data in a datatable (ex: dt). 将数据填写到数据表中(例如:dt)。 Then bind data directly to the gridview. 然后将数据直接绑定到gridview。 like 喜欢

Gridview.Datasource = dt; Gridview.Datasource = dt; Gridview.Databind(); Gridview.Databind();

Then Directly The headers will be displayed. 然后直接显示标题。

If you want to Display Location_Type as Location Type then you have to write SQL Query like this 如果要显示Location_Type作为Location Type则必须编写这样的SQL查询

Select Location_Type as [Location Type] .... from Tbl where 'Condition'

Logically this is not possible. 从逻辑上讲这是不可能的。 Because in this case you want to show rows of data in a single row with multiple column. 因为在这种情况下,您希望在多行的单行中显示数据行。 SO in case your location instance increases what will you do?? 所以,如果您的位置实例增加了,您会怎么做?

But if the number of location_instance is fixed then there is a work around. 但是,如果location_instance的数量是固定的,则可以解决。 But this is also limited. 但这也是有限的。 You can show the location instance as grid view row, not as column. 您可以将位置实例显示为网格视图行,而不是列。 You can style the row so that it will look like header. 您可以设置行的样式,使其看起来像标题。

To know how to convert a column data to a row data check the below link. 要了解如何将列数据转换为行数据,请查看以下链接。 http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/ http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/

So once you get the data in a row you can bind the data to the grid view easily by using RowDataBound of grid view. 因此,一旦连续获取数据,就可以使用网格视图的RowDataBound将数据轻松绑定到网格视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM