How to Create a Youtube Search with Paging in C#

By FoxLearn 7/16/2024 8:34:08 AM   17.7K
To create a YouTube search with paging using the YouTube Data API in a C# Windows Forms Application, you'll need to integrate the YouTube API, handle perform searches, and implement paging to display results in your application.

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

How to create a YouTube search with paging in C#

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

Here's an example of how you can perform a YouTube search with paging in C# using the YouTubeSearch package

Open your form designer, then drag and drop TextBox, Button and DataGridView controls from the Visual Studio toolbox to your winform, you can 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#

Next, 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; }
}

Adding 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;

Adding 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 this c# example, you've learned how to use youtube search api example c# .net

VIDEO TUTORIAL