为什么AsyncCallback不更新我的gridview?

时间:2010-04-06 12:33:31

标签: gridview asynchronous begininvoke

我上周开始与代表合作,我正在尝试在后台更新我的gridview异步。一切顺利,没有错误或类似但我没有得到我的EndInvoke后的结果。有谁知道我做错了什么?

以下是代码段:

    public delegate string WebServiceDelegate(DataKey key);

    protected void btnCheckAll_Click(object sender, EventArgs e)
    {
        foreach (DataKey key in gvTest.DataKeys)
        {
            WebServiceDelegate wsDelegate = new WebServiceDelegate(GetWebserviceStatus);
            wsDelegate.BeginInvoke(key, new AsyncCallback(UpdateWebserviceStatus), wsDelegate);
        }
    }

    public string GetWebserviceStatus(DataKey key)
    {
        return String.Format("Updated {0}", key.Value);
    }

    public void UpdateWebserviceStatus(IAsyncResult result)
    {
        WebServiceDelegate wsDelegate = (WebServiceDelegate)result.AsyncState;

        Label lblUpdate = (Label)gvTest.Rows[???].FindControl("lblUpdate");
        lblUpdate.Text = wsDelegate.EndInvoke(result);
    }

1 个答案:

答案 0 :(得分:0)

我刚刚按照您调用的顺序使用相同的异步调用运行测试。它在这里运行良好。我怀疑你在获取Label控件的句柄时遇到了问题。尝试将该行分成几行,以确保正确获得句柄。行实际上会返回一行吗? FindControl是否返回您想要的控件?您应该在两个函数中检查它。

作为旁注,您可能只想考虑索引到Rows并使用FindControl一次。您需要将传递给IAsyncResult的对象替换为可以保存Label句柄的对象。然后你可以做一次并分配它,然后在UpdateWebserviceStatus中使用。

编辑:试试这段代码。

        public delegate void WebServiceDelegate(DataKey key);

    protected void btnCheckAll_Click(object sender, EventArgs e)
    {
        foreach (DataKey key in gvTest.DataKeys)
        {
            WebServiceDelegate wsDelegate = new WebServiceDelegate(GetWebserviceStatus);
            wsDelegate.BeginInvoke(key, new AsyncCallback(UpdateWebserviceStatus), wsDelegate);
        }
    }

    public void GetWebserviceStatus(DataKey key)
    {
        DataRow row = gvTest.Rows[key.Value];
        System.Diagnostics.Trace.WriteLine("Row {0} null", row == null ? "is" : "isn't");

        Label lblUpdate = (Label)row.FindControl("lblUpdate");
        System.Diagnostics.Trace.WriteLine("Label {0} null", lblUpdate == null ? "is" : "isn't");

        lblUpdate.Text = string.Format("Updated {0}", key.Value);
    }

    public void UpdateWebserviceStatus(IAsyncResult result)
    {
    WebServiceDelegate wsDelegate = (WebServiceDelegate)result.AsyncState;
    DataKey key = wsDelegate.EndInvoke(result);
    }
相关问题