Windows Forms: Youtube Search with Paging in C#

This post shows you how to create a youtube search with paging using youtube search api in c# .net windows forms application.

YoutubeSearch is a library for .NET, written in c# .net that helps you get the search query results from YouTube.

To create a youtube search data, you need to install the YouTubeSearch library to your project by right-clicking on your project, then select Manage NuGet Packages -> Search youtubesearch -> Install

Drag the TextBox, Button and DataGridView from the visual studio toolbox to your winform, then design a simple UI that allows you to enter the video name, then return search query results from the youtube and display data to the DataGridView as shown below.

youtube search in c#

First off, you need to create the Video class that helps you map data return from youtube site.

public class Video
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string Url { get; set; }
    public Image Thumbnail { get; set; }
}

Add the click event handler to the Search button that allows you to search the video name from youtube, then set the DataSource of DataGridView to the search results as the following c# code.

private void btnSearch_Click(object sender, EventArgs e)
{
    VideoSearch items = new VideoSearch();
    List<Video> list = new List<Video>();
    //Search video with paging
    foreach (var item in items.SearchQuery(txtSearch.Text, pageNumber))
    {
        Video video = new Video();
        video.Title = item.Title;
        video.Author = item.Author;
        video.Url = item.Url;
        //Get thumbnail
        byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
        using (MemoryStream ms = new MemoryStream(imageBytes))
        {
            video.Thumbnail = Image.FromStream(ms);
        }
        list.Add(video);
    }
    //Add videos to datagridview
    videoBindingSource.DataSource = list;
}

You should create the pageNumber variable to help you store current page.

int pageNumber = 1;

Add the click event handler to the Back button allows you to go back page.

private void btnBack_Click(object sender, EventArgs e)
{
    if (pageNumber > 1)
    {
        pageNumber--;
        btnSearch_Click(null, null);
    }
}

Finally, Add the click event handler to the Next button that allows you to search to next page.

private void btnNext_Click(object sender, EventArgs e)
{
    pageNumber++;
    btnSearch.PerformClick();
}

Through the c# example above, you've learned how to use youtube search api example c# .net

VIDEO TUTORIAL