【问题标题】:Add item to Listview from function将项目从函数添加到 Listview
【发布时间】:2019-09-24 03:57:51
【问题描述】:

我正在尝试在我的 listView1 中添加一行。我如何在另一个函数中做到这一点?

我正在阅读this 的帖子。他们希望我直接将其添加到按钮功能中。我不想那样做。

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

我希望它在这里listView1.Items.Add(listViewItem); 的 listView1 中添加一行,但我收到一条错误消息说

非静态字段、方法或属性“Form1.listView1”需要对象引用

【问题讨论】:

  • 从public static async中删除static
  • 或者删除你不需要的static async...你不是await ing任何东西...
  • 我认为他会添加一些与异步相关的东西(如函数名称所示)
  • @Çöđěxěŕ 这个东西string[] row = { id, seller, product, betTime, price + shipping, link };可能来自http客户端,
  • 您遇到的问题应该得到解决,但您提到您还有另一个问题,but then i get another error cus i need the static for other stuff inside the function。如果是这种情况,请更新您的帖子,以便我们更好地为您提供帮助。

标签: c# listview listviewitem


【解决方案1】:

所以根据你的要求试试这个。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    相关资源
    最近更新 更多