如何在asp.net中异步显示GridView中的数据?

时间:2018-12-23 14:46:42

标签: c# asp.net asynchronous async-await

我的代码在桌面应用程序中正常工作,无法正常显示数据 在数据gridview中,但是当我在Web表单中使用相同的代码时,它会抛出 GridView1为空。 GridView1.DataSource =表; 。 调试数据完全可以正常工作,只是想将数据放入 gridview。要完成任务我应该做些什么改变。

    public partial class _Default : System.Web.UI.Page
    {
        public class NameAndScore
        {
            public string Name { get; set; }
            public string Score { get; set; }
        }
     public _Default()
     {

        InitTable();
     }
        DataTable table;
        HtmlWeb web = new HtmlWeb();

        private async Task<List<NameAndScore>> GameRankingsFromPage(int pagenum)
        {
            string url = "https://www.ebay.com/sch/i.html?_nkw=xbox+one&_in_kw=1&_ex_kw=&_sacat=0&LH_Complete=1&_udlo=&_udhi=&_ftrt=901&_ftrv=1&_sabdlo=&_sabdhi=&_samilow=&_samihi=&_sadis=15&_stpos=&_sargn=-1%26saslc%3D1&_salic=1&_sop=12&_dmd=1&_ipg=50&_fosrp=1";
            //    string url = "https://www.gamerankings.com/browse.html";

            if (pagenum != 0)
                url = "https://www.ebay.com/sch/i.html?_sacat=0&LH_Complete=1&_udlo=&_udhi=&_ftrt=901&_ftrv=1&_sabdlo=&_sabdhi=&_samilow=&_samihi=&_sadis=15&_stpos=&_sop=12&_dmd=1&_fosrp=1&_nkw=xbox+one&_pgn=" + pagenum.ToString() + "&_skc=50&rt=nc";

            var doc = await Task.Factory.StartNew(() => web.Load(url));

            var namenodes = doc.DocumentNode.SelectNodes("//*[contains(@id,'item')]/h3/a");
            var scorenodes = doc.DocumentNode.SelectNodes("//*[contains(@id,'item')]/ul[1]/li[1]/span");
            var names = namenodes.Select(node => node.InnerText.Trim('\r', '\n', '\t'));
            var scores = scorenodes.Select(node => node.InnerText.Trim('\r', '\n', '\t'));


            if (namenodes == null || scorenodes == null)
                return new List<NameAndScore>();

            return names.Zip(scores, (name, score) => new NameAndScore() { Name = name.ToString(), Score = score.ToString() }).ToList();
        }
        protected async void Page_Load(object sender, EventArgs e)
        {
            int pageNume = 0;
            int id = 0;
            var rankings = await GameRankingsFromPage(0);
            while (rankings.Count > 0)
            {
                foreach (var ranking in rankings)
                     table.Rows.Add(id++, ranking.Name, ranking.Score);
                GridView1.DataSource = table;
                GridView1.DataBind();
                pageNume++;
                rankings = await GameRankingsFromPage(pageNume);
            }

        }
        private void InitTable()
        {
            table = new DataTable("Xbox Prices");
            table.Columns.Add("ID", typeof(string));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Score", typeof(string));
            GridView1.DataSource = table;
            GridView1.DataBind();

        }
    }

0 个答案:

没有答案