C# / .Net Youtube V3 API, 发布要控制的列表项

C# / .Net Youtube V3 API, Issue listing items to control

我目前正在使用 YouTube API 进行一个小型测试项目。 我想要实现的目标非常简单:我使用 API 进行搜索请求,获取标题和视频 ID,然后将它们放入 DataTable 中。 从那里我想从每个结果中制作一个按钮并将它们添加到 FlowLayoutPanel 所以我认为是使用 foreach 循环。但是这里出现的问题是当我得到超过 100 个结果时它似乎会抛出错误(我猜 windows 表单不喜欢制作 100+ 个按钮)

我想知道的是我能否使我的代码更有效率,例如我能否在下面添加 2 个按钮以显示 "next" 和 "previous" 100 个结果。所以它一次只会加载100个。

下面是我的代码,可能有点乱,因为我是 c# 的新手。

这是我用来开始搜索的按钮。

    private void Youtube_Search_Video_Button_Click(object sender, EventArgs e)
    {
        string Search_Vid = Youtube_SearchVideo_Box.Text;
        if (Youtube_SearchVideo_Box.Text == "Search video" || Youtube_SearchVideo_Box.Text == "")
        {
            Youtube_SearchVideo_Box.Text = "Search video";
        }
        if (Search_Vid != null && Search_Vid != "Search video" && Search_Vid != Last_Search_Vid)
        {
            Last_Search_Vid = Youtube_SearchVideo_Box.Text;

            search_results_vids.Clear();
            if (search_results_vids.Columns.Count.Equals(0)) {
                search_results_vids.Columns.Add("VideoTitle");
                search_results_vids.Columns.Add("VideoID");
            }

            flowLayoutPanel1.Controls.Clear();
            toolStripStatusLabel1.Text = "Status : Searching...";
            backgroundWorker1.RunWorkerAsync();
        }
    }

这将启动下面的后台程序。 (哦,当然还有在那之前创建的数据table。)

    public DataTable search_results_vids = new DataTable();


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
        {
            ApplicationName = this.GetType().ToString(),
            ApiKey = "MyApiKeY",
        });
        var nextPageToken = "";
        while (nextPageToken != null)
        {
            var listRequest = youtube.Search.List("snippet");
            listRequest.Q = Youtube_SearchVideo_Box.Text;
            listRequest.MaxResults = 50;
            listRequest.Type = "video";
            listRequest.PageToken = nextPageToken;

            var resp = listRequest.Execute();
            List<string> videos = new List<string>();

            foreach (SearchResult result in resp.Items)
            {
                switch (result.Id.Kind)
                {
                    case "youtube#video":
                        object[] newsearchresult = { result.Snippet.Title, result.Id.VideoId};
                        search_results_vids.Rows.Add(newsearchresult);

                        break;
                }

            }

            nextPageToken = resp.NextPageToken;

        }


    }

当它完成时。

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        foreach (DataRow row in search_results_vids.Rows)
        {

            Button button = new Button();
            button.Text = row["VideoTitle"].ToString();
            if (button.Text.Length >= 35)
            {
                button.Text.Remove(button.Text.Length - (button.Text.Length - 35));
            }
            button.Tag = row["VideoID"];
            button.TextImageRelation = TextImageRelation.ImageBeforeText;
            button.FlatStyle = FlatStyle.Flat;
            button.ForeColor = Color.LightSteelBlue;
            button.BackColor = Color.SteelBlue;
            button.Width = (flowLayoutPanel1.Width - 120);
            button.TextAlign = ContentAlignment.MiddleLeft;
            button.Height = 35;
            button.Font = new Font(button.Font.FontFamily, 10);
            flowLayoutPanel1.Controls.Add(button);

        }
        toolStripStatusLabel1.Text = "Status : Listing Videos, Please Wait...";
        toolStripStatusLabel2.Text = "Results : " + search_results_vids.Rows.Count.ToString();

    }

我试过将 Foreach 循环添加到后台工作程序的 DoWork 部分,但它似乎一起跳过了它。非常欢迎任何帮助,如果我做错了什么,请告诉我(还在学习中!)

编辑:为了澄清这是我坚持的按钮创建部分。将 table 中的项目列出到列表视图可以正常工作。所有按钮设置似乎都与它们的加载时间有关。所以这就是为什么我想尝试一种方法,我从数据表中每个 "page" 只加载 100 个。我只是不知道如何处理这个问题。

我认为您应该考虑将结果放入页面中。

YouTube API - Pagination

是的,您可以在同一循环中添加按钮(backgroundWorker1_DoWork),只需确保 Adding/Changing UI 应该在不同的循环中线程 ...否则你会得到跨线程异常。 所以一种方法是

 Action actUI = ()=>{

                      Button button = new Button();
                      button.Text = get Data from newsearchresult ;
                      if (button.Text.Length >= 35)
                      {
                         button.Text.Remove(button.Text.Length - (button.Text.Length - 35));
                      }
                     button.Tag = get Data from newsearchresult ;;
                     button.TextImageRelation = TextImageRelation.ImageBeforeText;
                     button.FlatStyle = FlatStyle.Flat;
                     button.ForeColor = Color.LightSteelBlue;
                     button.BackColor = Color.SteelBlue;
                     button.Width = (flowLayoutPanel1.Width - 120);
                     button.TextAlign = ContentAlignment.MiddleLeft;
                     button.Height = 35;
                     button.Font = new Font(button.Font.FontFamily, 10);
                     flowLayoutPanel1.Controls.Add(button);
                  };

            if(flowLayoutPanel1.InvokeRequired)
              flowLayoutPanel1.BeginInvoke(actUI);
            else
              flowLayoutPanel1.Invoke(actUI);