ASP.NET:Access ListView';以编程方式创建数据源对象

ASP.NET:Access ListView';以编程方式创建数据源对象,asp.net,listview,sqldatasource,selectcommand,Asp.net,Listview,Sqldatasource,Selectcommand,我已将ListView绑定到数据库。我已经使用SqlDataSource来完成这项工作。我想以编程方式更改数据源,但这就是问题所在。我尝试通过以下方式获取当前数据源: SqlDataSource oldSource = lstContacts.DataSource as SqlDataSource; 然后,我想将SqlDataSource的SelectCommand保存为字符串: string oldSelectCommand = oldSource.SelectCommand; 我这样做是

我已将ListView绑定到数据库。我已经使用SqlDataSource来完成这项工作。我想以编程方式更改数据源,但这就是问题所在。我尝试通过以下方式获取当前数据源:

SqlDataSource oldSource = lstContacts.DataSource as SqlDataSource;
然后,我想将SqlDataSource的SelectCommand保存为字符串:

string oldSelectCommand = oldSource.SelectCommand;
我这样做是因为我想检查select语句是否包含ORDERBY子句,如果包含,则将其删除并使用另一个ORDERBY子句进行更改:)

然而,我得到的是:

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

有人吗?请(:

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

<asp:ListView ID="ListView1" runat="server" 
    DataKeyNames="AccountID" DataSourceID="SqlDataSource1" >
在守则中:

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();
}

希望有帮助!

在标记中设置ListView的DataSourceID时会出现这种情况,如下所示:

<asp:ListView ID="ListView1" runat="server" 
    DataKeyNames="AccountID" DataSourceID="SqlDataSource1" >
在守则中:

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();
}

希望有帮助!

此处询问的类似问题-,没有解决方案。此处询问的类似问题-,没有解决方案。感谢您的回答!我就是这么做的:我将最后一个select命令存储在ViewState集合中,每次在排序下拉列表上发生所选项目更改事件时,我都会收到select命令,对其进行修改,然后将列表绑定为a增益:)现在一切正常:)谢谢你的回答!这就是我所做的:我将最后一个select命令存储在ViewState集合中,每次在“排序”下拉列表中发生“选定项更改”事件时,我都会获取select命令,对其进行修改,然后再次绑定列表:)现在一切正常:)