我有一个 GridView,它的 DataSourceID 指向 ObjectDataSource。 ObjectDataSource 指向一个通过使用 ObjectDataSource 控件的 TypeName、SelectMethod 和 SelectCountMethod 属性返回 LINQ IQueryable 的方法。所发生的情况是数据预先正确加载。但是,在回发时,如果我从 GridView 中删除行并尝试使用显式 GridView.DataBind() 重新绑定(bind),则它不起作用。我知道 LINQ 返回正确的行计数等,因为我调用了 count 方法并且它返回正确的行计数。这是一个简单的示例:
<asp:GridView ID="TestGridView" runat="server" PageSize="20"
AutoGenerateColumns="false" AllowPaging="true"
AllowSorting="false" DataSourceID="TestDataSource">
<Columns>
...
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="TestDataSource" runat="server"
EnablePaging="true" SelectCountMethod="GetDetailCount"
SelectMethod="GetDetails" TypeName="MyApp.PageClass" />
我尝试添加一个按钮并添加 TestGridView.DataBind();方法。我尝试将其添加到 Page_PreRender 事件中。无论我尝试什么,它都不起作用。
正如下面有人建议的那样,我也尝试将其移动到 Page_Load,但没有成功。这是我的代码的一个粗略示例:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Set "initial" query parameters, then ...
BindData();
}
}
private void BindData()
{
// EDITED: Removed the code below since I'm not looking to delete the
// rows from the database, but rather get the GridView to rebind
// which its not.
////Remove all current rows from the GridView
//int colCount = TestGridView.Rows.Count;
//for (int x = 1; x <= colCount; x++)
//{
// TestGridView.DeleteRow(x);
//}
// Bind GridView to the ObjectDataSource
TestGridView.DataBind();
}
protected void RegenerateImageButton_Click(object sender, ImageClickEventArgs e)
{
// Set "updated" query parameters, then ...
BindData();
}
最佳答案
Gridview 不会在回发时重新绑定(bind),它们的行会从 View 状态中拉回。在页面加载(或初始化?)时将gridview的DatasourceID重置为对象数据源ID将导致gridview反弹。
关于asp.net - 回发后 GridView 未正确重新绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1759325/