c# - 在 ASP.Net Gridview 中使用 session 变量

标签 c# asp.net

我有一个 session 变量,它保存当前登录用户的详细信息。我想根据变量运行查询并将其显示在 GridView 中。 我想用 session 变量替换 GridView 的默认值,但这没有用。

谁能指出我正确的方向?

这是我尝试过的:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:..... %>" 

    SelectCommand="SELECT [Username], [Password], [CustomerName], [CustomerAddress], [Contact] FROM [Customers] WHERE ([Username] = @Username)">
    <SelectParameters>
        <asp:Parameter DefaultValue="session[new]" Name="Username" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

最佳答案

您可以在 SqlDataSource 使用数据源的 Selecting 事件执行查询之前提供 Session 变量值。使用 OnSelecting 属性在标记中设置此事件。

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:..... %>" 
    OnSelecting="SqlDataSource1_Selecting"
    SelectCommand="SELECT [Username], [Password], [CustomerName], [CustomerAddress], [Contact] FROM [Customers] WHERE ([Username] = @Username)">
    <SelectParameters>
        <asp:Parameter Name="Username" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

在 Selecting Event Handler 中,您可以执行以下操作:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e) 
    { 
          if(Session["UserName"]!=null)
           {
           // do this only when Session Variable stores as a string the Username
           e.Command.Parameters["@Username"].Value = Session["UserName"];
           }
         else
           {
              // assign the default value if session variable is Null
              e.Command.Parameters["@Username"].Value ="DefaultValue";
            }

    }

在此事件处理程序中,您可以通过 SqlDataSourceSelectingEventArgs.Command 属性,并以编程方式修改其参数值。

关于c# - 在 ASP.Net Gridview 中使用 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17869186/

相关文章:

c# - 确定文件夹是否在 .NET 中共享

c# - IObserver -- 当 IObserver.OnError 被调用时,观察者应该做什么

c# - Microsoft JScript 运行时错误 : Unable to get value of the property 'style' : object is null or undefined

c# - 跨页发布 GridView

c# - 如何在不提及派生类名称的情况下返回接口(interface)类型?

C# 回滚 Streamreader 1 个字符

c# - MEF组成问题

asp.net - 如何从 IIS7 中删除 eTag header ?

c# - 在指定次数的登录失败后阻止用户

c# - ASP MVC 应用程序在长时间运行的线程上重置