1
votes

I'm trying to add a row in my listView1. How do i do this in another function?

I was reading this post. And they want me to add it directly in a button function. I don't want to do that.

private void button1_Click(object sender, EventArgs e)
{
    keyword();
}

public static void keyword()
{
    string country = "";
    string key = "1070";

    //Goto GetHtmlAsync
    GetHtmlAsync(key, country);
}

public static async void GetHtmlAsync(string key, string country)
{
    //GetHtmlAsync
    var url = "https://www.test.com/search?county=" + country + "&q=" + key;

    var httpClient = new HttpClient();
    var html = await httpClient.GetStringAsync(url);

    var htmlDocument = new HtmlDocument();
    htmlDocument.LoadHtml(html);

    //This is grabbed from HtmlDocument (list)
    var id = "58756";
    var seller = "Test";
    var product = "GTX 1070";
    var betTime = "10:10";
    var price = "100";
    var shipping = "4";

    string[] row = { id, seller, product, betTime, price + shipping, url };
    var listViewItem = new ListViewItem(row);
    listView1.Items.Add(listViewItem);
}

I expect it to add a row in the listView1 here listView1.Items.Add(listViewItem);, but i get an error message saying

An object reference is required for the non-static field, method, or property 'Form1.listView1'

1
Remove static from public static async - fhnaseer
Or remove static async which you don't need any of it... you are not await ing anything... - zaggler
I think he will add something related to async (as function name says) - fhnaseer
@Çöđěxěŕ This thing string[] row = { id, seller, product, betTime, price + shipping, link }; might come from http client, - fhnaseer
The problem you had should be resolved, but you mentioned you have another issue, but then i get another error cus i need the static for other stuff inside the function. If this is the case, update your post so we can better assist you. - zaggler

1 Answers

0
votes

So according to your requirements try this.

private void button1_Click(object sender, EventArgs e)
{
    keyword();
}
// Non static so that you can access ListView1
public void keyword()
{
    string country = "";
    string key = "1070";

    //Goto GetHtmlAsync
    GetHtmlAsync(key, country);
}
// Non static
public async void GetHtmlAsync(string key, string country)
{
    //GetHtmlAsync
    var url = "https://www.test.com/search?county=" + country + "&q=" + key;

    var httpClient = new HttpClient();
    var html = await httpClient.GetStringAsync(url);

    var htmlDocument = new HtmlDocument();
    htmlDocument.LoadHtml(html);

    //This is grabbed from HtmlDocument (list)
    var id = "58756";
    var seller = "Test";
    var product = "GTX 1070";
    var betTime = "10:10";
    var price = "100";
    var shipping = "4";

    string[] row = { id, seller, product, betTime, price + shipping, url };
    var listViewItem = new ListViewItem(row);
    listView1.Items.Add(listViewItem);
}