ASP.NET:以编程方式访问ListView的DataSource对象

时间:2013-09-02 17:13:41

标签: asp.net listview sqldatasource selectcommand

我将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."

任何?请(:

1 个答案:

答案 0 :(得分: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进行数据绑定,则可以访问它们,直到有任何postback.ListView DataSource未存储在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();
}

希望它有所帮助!