Search code examples
c#asp.netradio-buttoncode-behindsearchbar

ASP.NET and C#: create button that sends keyword to website with search bar


I am new to ASP.NET and C#. In a Web App, I know I can create a button that opens a webpage:

private void button1_Click(object sender, EventArgs e)
{
    //Launch browser
    System.Diagnostics.Process.Start("https://www.nhl.com/jets");
}

But if the landing page has a search bar, how can I send a keyword to that search bar upon clicking the button? For clarity, say that my code-behind declares that keyword like this: string keyword = Keyword.Text. How can I make sure that this keyword is automatically sent to the search bar, so that users can see the results without having to type the keyword?


Solution

  • Try this, you should use webBrowser automation. i adapted this methods i wrote before to your website, just add your little adjustments:

    ... string keyboard = Keyword.Text
    
        public String GetKeyboardValueForSearch() {
            return keyboard;
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.DocumentCompleted += new 
            WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            webBrowser1.Navigate("https://www.nhl.com/jets");            
        }
    
        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlElement search = webBrowser1.Document.GetElementById("top-nav__search- 
            autocomplete__input");
            if(search != null)
            {
                search.SetAttribute("value", GetKeyboardValueForSearch());
                foreach(HtmlElement ele in search.Parent.Children)
                {
                    if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
                    {
                        ele.InvokeMember("click");
                        break;
                    }
                }
            }
        }