ASP.Net 数据源导航

ASP.Net datasource navigation

找了一段时间,没有找到合适的解决办法;我正在尝试在 ASP.Net 页面中包含用户名和详细信息的数据集(它是 gridView 的来源)中进行搜索。

如果用户想查找特定的行,他需要输入用户名,然后按一个按钮。然后,我想更改保存在缓存中的数据集 - 我希望它包含用户正在搜索的特定行。

但是,当我更改数据集(将其设置为仅包含一行)时,出现以下错误:

A field or property with the name 'Username' was not found on the selected data source.

我做错了什么吗?

代码如下:

protected void Search_Click(object 
        sender, EventArgs e)
    {
        DataRow myRow = findRow(((DataSet)Cache["Users"]).Tables[0], userSearched.Text);
        if (myRow == null)
        {
            ResponseLabel.ForeColor = System.Drawing.Color.Red;
            ResponseLabel.Text = "User not found.";
            return;
        }
        ResponseLabel.ForeColor = System.Drawing.Color.Green;
        ResponseLabel.Text = "There you go.";
        DataSet newDs = new DataSet();
        DataTable newDt = new DataTable();
        newDt.ImportRow(myRow);
        newDs.Tables.Add(newDt);
        Cache["Users"] = newDs;
        UpdateSource(); // Updating the source after each iteration
        }

findrow():

private DataRow findRow(DataTable View, string searchValue, int index = 0)
    {
        foreach (DataRow row in View.Rows)
        {
            if (row.ItemArray[index].Equals(searchValue))
            {
                return row;
            }
        }
        return null;
    }

GridView中的相关部分:

<Columns>
        <asp:BoundField DataField="Username" HeaderText="Username" 
            SortExpression="Username" />
        <asp:BoundField DataField="TimeJoined" HeaderText="Joined" 
            SortExpression="TimeJoined" />
        <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
        <asp:CheckBoxField DataField="Banned" HeaderText="Banned" 
            SortExpression="Banned" />
        <asp:CheckBoxField DataField="Admin" HeaderText="Admin" 
            SortExpression="Admin" />
        <asp:CommandField HeaderText="Options" ShowEditButton="True" 
            ShowHeader="True" />
    </Columns>

页面加载:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Cache["Users"] == null)
            {
                UsersView.DataSource = DbManager.getUsersView(); // database stuff. It worked pretty well before.
                Cache["Users"] = UsersView.DataSource;
            }
            else
            {
                UsersView.DataSource = (DataSet)Cache["Users"];
            }
            UsersView.DataBind(); // I get the error here.
        }
    }

如果您还需要什么,请告诉我。提前致谢!

我相信您在 Search_Click 中重新创建 DataTable 架构时会丢失它,请尝试显式声明列名。

顺便说一句,您是否尝试过 DataTable Select 方法 (https://msdn.microsoft.com/en-us/library/y06xa2h1.aspx) or a DataView (https://msdn.microsoft.com/en-us/library/bb669073%28v=vs.110%29.aspx)?