当您在标记中设置 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 数据源未存储在视图状态中,因此在您设置数据源并再次重新绑定 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();
}
希望能帮助到你!