将数据绑定到Gridview固定行,变量列

时间:2014-11-21 23:22:54

标签: c# asp.net gridview

我正在尝试编写一个Web应用程序来收集用户计数以进行审计。我有一个可以运行的Oracle查询(我在SQL Developer中运行它),但是我试图通过网络为超级用户提供这个报告来提取自己的计数而不是依赖我。我在gridview中显示数据时遇到问题。

Oracle Query(使用硬编码固定数量的用户):

select * from (
select ad.display_name, ev.creator from auditdefinition ad, event ev 
where ad.event_class_id = ev.object_class_id and ev.create_date >= to_date('01-OCT-2014','dd-MON-yyyy') and ev.create_date < to_date('01-DEC-2014','dd-MON-yyyy')
)
pivot 
(
count(creator)
for creator in ('user1','user2','user3','user4')
)
order by display_name;

结果显示如下:

------------------------------------------
|        | user1 | user2 | user3 | user4 |
------------------------------------------
| Create | 5     | 2     | 8     | 15    |
------------------------------------------
| Delete | 9     | 6     | 10    | 1     |
------------------------------------------
| View   | 123   | 461   | 84    | 89    |
------------------------------------------
***note:  Create, Delete, View are from "display_name" from the query

我知道如何在&#34; Columns&#34;是固定的(我做了另一个表与不同的查询),但因为我不知道有多少&#34; userX&#34;会有,我不知道如何在网络中动态构建它并将其显示在网格中。

GridView的aspx代码:

<asp:GridView AutoGenerateColumns="False" CellPadding="2" CellSpacing="2" GridLines="none" HorizontalAlign="Left" ID="GridView2" runat="server">
        </asp:GridView>

幕后的aspx.cs代码:

DataSet ds = new DataSet();

DataTable dt = ds.Tables.Add("Amount");
//I would normally add my columns here if they were fixed but because it it dynamic, I am not sure



...

GridView2.DataSource = dt; //beginning to bind my DataTable
GridView2.DataBind();

2 个答案:

答案 0 :(得分:0)

如果可以从表中读取user1,user2和usern说tb_users,那么它将使您的脚本更容易。

select * from (
select ad.display_name, ev.creator from auditdefinition ad, event ev 
where ad.event_class_id = ev.object_class_id and 
ev.create_date >= to_date('01-OCT-2014','dd-MON-yyyy') and 
ev.create_date < to_date('01-DEC-2014','dd-MON-yyyy'))
pivot 
(
count(creator)
for creator in (select username from tb_users)
)
order by display_name;

如果您这样做,请在Web表单上下拉并将其绑定到表tb_users

在此下拉菜单的选择事件中,您可以将gridview与针对用户选择的数据绑定。

答案 1 :(得分:0)

每当您在GridView控件中说AutoGenerateColumns="False"时,您需要指定包含所有列及其各自数据值的Columns标记。既然你说你不知道有多少“userX”,那么让GridView控件为你绑定数据,只需将想要在GridView中看到的数据正确传递给DataTable \ DataSet并设置AutoGenerateColumns属性true: -

<asp:GridView AutoGenerateColumns="True" CellPadding="2" CellSpacing="2" GridLines="none" HorizontalAlign="Left" ID="GridView2" runat="server">
</asp:GridView>

<强>更新: -

您可以使用dataadapter直接获取并填充数据集: -

string CS = "Your connection string";
using (SqlConnection conn = new SqlConnection(CS))
{
    SqlDataAdapter da = new SqlDataAdapter("SPName", conn);
    da.SelectCommand.CommandType = CommandType.StoredProcedure;
    da.SelectCommand.Parameters.Add("@yourParam", SqlDbType.Int/*Your datatype*/).Value = 123;
    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView2.DataSource = ds;
    GridView2.DataBind();
}
相关问题