【问题标题】:ASP.NET: Access ListView's DataSource object programaticallyASP.NET:以编程方式访问 ListView DataSource 对象
【发布时间】:2013-09-05 20:20:37
【问题描述】:

我已将我的 ListView 绑定到数据库。我已经使用 SqlDataSource 来完成这项工作。我想以编程方式更改数据源,但这就是一切都出错的地方。我尝试通过这样做来获取当前数据源:

SqlDataSource oldSource = lstContacts.DataSource as SqlDataSource;

那我想把SqlDataSource的SelectCommand保存成一个字符串:

string oldSelectCommand = oldSource.SelectCommand;

我这样做是因为我想检查 select 语句是否包含 order by 子句,如果包含,则将其删除并用另一个 order by 子句进行更改:)

但是,我得到了这个:

"System.NullReferenceException: Object reference not set to an instance of an object."

有人吗?请(:

【问题讨论】:

标签: asp.net listview sqldatasource selectcommand


【解决方案1】:

当您在如下标记中设置 ListView 的 DataSourceID 时会发生这种情况:

<asp:ListView ID="ListView1" runat="server" 
    DataKeyNames="AccountID" DataSourceID="SqlDataSource1" >

The property DataSource is null if the binding comes by the DataSourceID property.

如果您在代码中对 ListView 进行数据绑定,则可以访问它们,直到有任何回发为止。ListView 数据源未存储在 viewstate 中,因此在您设置数据源并重新绑定 ListView 之前它会丢失。

解决方法: 在给定的场景中,我将使用隐藏字段来存储 Order By 子句,并在代码中设置 ListView 的数据源:

<asp:HiddenField ID="hdnOrderBy" runat="server" />
    <asp:ListView ID="ListView1" runat="server" DataKeyNames="AccountID">
        ... ... ...

在代码中:

private void BindListView()
{
    string orderBy = hdnOrderBy.Value;
    //Your conditions here
    if (orderBy.Contains("By AccountID"))
    {
        orderBy = " Order By CompanyName";
        hdnOrderBy.Value = orderBy;
    }

    string selectCommand = "SELECT [AccountID], [CompanyName], [CompanyID]  FROM [Account] ";
    SqlDataSource1.SelectCommand = String.Format("{0} {1}",selectCommand,orderBy);
    ListView1.DataSource = SqlDataSource1;
    ListView1.DataBind();
}

希望对你有帮助!

【讨论】:

  • 感谢您的回答!这就是我所做的:我将最后一个选择命令存储在 ViewState 集合中,并且每次在排序下拉列表中发生所选项目更改事件时,我都会获得选择命令,对其进行修改,然后再次绑定列表:) 现在一切正常:)
猜你喜欢
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多