【问题标题】:C# / .Net Youtube V3 API, Issue listing items to controlC# / .Net Youtube V3 API,问题列表项控制
【发布时间】:2016-03-03 05:31:20
【问题描述】:

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

我想知道的是,我能否让我的代码更高效,例如,我能否在下方添加 2 个按钮来显示“下一个”和“上一个”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();
        }
    }

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

    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 部分,但它似乎一起跳过了它。非常欢迎任何帮助,如果我做错了什么,请告诉我(仍在学习!)

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

【问题讨论】:

    标签: c# .net visual-studio-2015 youtube-data-api


    【解决方案1】:

    是的,你可以在同一个循环中添加按钮(backgroundWorker1_DoWork),只要确保添加/更改 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);
    

    【讨论】:

    • 嘿,这似乎很有帮助!但是我最近才开始使用 c#,所以您能否指出我可以阅读更多有关此内容的正确方向?我已经阅读了一些关于 InvokeRequired 的内容,并认为我需要它来让 UI 部分在后台工作人员中工作。但我还不太了解它的用途。 button.Tag = get Data from newsearchresult 也是如此;得到正确的项目,它怎么知道拿第二个项目? (对不起,菜鸟问题哈哈)
    • 对不起另一个问题:我假设 flowlayoutpanel invokerequired 部分进入循环?但是我在哪里添加操作?
    【解决方案2】:

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

    YouTube API - Pagination

    【讨论】:

    • 嗯,但 youtube 搜索并不是在后台工作人员中只需要 2 秒的问题。我只能在列表视图中将其列为文本,并且一切正常。问题是当我要求它创建所有这些按钮而不是列表视图格式时,表单应用程序只是放弃了。所以我想我要问的是如何对数据表进行分页?附言。我已经对搜索结果使用了分页 listRequest.PageToken = nextPageToken;
    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2014-07-02
    • 2014-09-11
    • 1970-01-01
    • 2013-09-19
    • 2017-11-01
    • 2011-08-22
    相关资源
    最近更新 更多