Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is properly work in desktop application show data asynchronously in data gridview but when I use same code in web form it throws exception GridView1 was null. at GridView1.DataSource = table;.While debugging data is completely working just want to put that data into webform gridview.What changes should i made to acheive my task.


What I have tried:

public partial class _Default : System.Web.UI.Page
{
    public _Default()
    {

        InitTable();
    }

    public class NameAndScore
    {
        public string Name { get; set; }
        public string Score { get; set; }
    }
   
    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);
            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();

    }
Posted
Updated 1-Jan-19 0:38am
Comments
F-ES Sitecore 1-Jan-19 8:47am    
If you think this is going to gradually fill the table in the browser then that's not going to happen. In asp.net the server waits until all your code has run and all your html has been generated before sending the html to the browser in one go.

I replicated your scenario on my system. I have to made few changes, like binding gridview after data has been mapped into table. Also, while block seems to be creating an infinite loop, so i have to comment out that (you might need to check that logic again). Here is the final code and it worked for me and i can see data on the web page

protected async void Page_Load(object sender, EventArgs e)
	{
		InitTable();
		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);
			pageNume++;
			rankings = await GameRankingsFromPage(pageNume);
		//}

		GridView1.DataSource = table;
		GridView1.DataBind();
	}

	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();

	}
 
Share this answer
 
Comments
Arslan jappa 2-Jan-19 12:11pm    
I really appreciate all the hard work you’ve done to help me.but now Application is getting data contain just first 50 products from first page of website not from other pages. In desktop application gridview asynchronously fill mean first add 50 products then after few second it again add 50 products.But in webform when I comment while condition page do not stop loading bxz the problem is gridview is not configurable asynchronously.do you have any idea to make that async. ?thanks
AnkushK1 4-Jan-19 11:33am    
I never worked practically, but using ajax this is certainly doable. You can refer to below link:
https://www.aspsnippets.com/Articles/Bind-Load-GridView-after-Page-load-is-completed-using-AJAX-UpdatePanel-in-ASPNet.aspx
This is because, page constructor gets invoked before page_load event. You can not access any ASP.NET control in constructor because they are loaded after constructor call. In simple terms, if you want to use any control in ASP.NET, it must be in Page_Load or any other method of page life cycle rather than constructor. You might want to go through page life cycle events using below url

ASP.NET Page Life Cycle Overview | Microsoft Docs[^]
 
Share this answer
 
Comments
Arslan jappa 28-Dec-18 1:14am    
so where should I put my control to get output in this scenario.?
AnkushK1 28-Dec-18 12:51pm    
You can either use Page_Init event which is the first to invoke when controls are initialized, however Page_Load should also work for you since it is raised after Page_Init. So you will be able to get your GridView in both of these events.
Arslan jappa 30-Dec-18 5:02am    
I have put inittable in pageLoads still not working.
AnkushK1 30-Dec-18 11:42am    
You mean still getting null exception? Can you share the code that you added?
Arslan jappa 1-Jan-19 1:26am    
bro I just Put InitTable() function in pageload and remove from constructor.actually This code scrap data from website like get price and name of mobile etc and working perfectly.But I want to implement in web form.I think gridview load as soon as program start before getting data from website that the reason program throw null exception.I dont know what changes I can make to run in webform thats my goal.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900