Get and Set the value of an input element In Selenium using C#

Get the Value of an Input Element:

To retrieve the current value of an input element, you can use the GetAttribute method to fetch the “value” attribute. Here’s an example:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

class Program
{
    static void Main(string[] args)
    {
        // Create a new instance of the Chrome driver
        IWebDriver driver = new ChromeDriver();

        // Navigate to your web page
        driver.Navigate().GoToUrl("your_website_url_here");

        // Find the input element by its ID (replace with your element's ID)
        IWebElement inputElement = driver.FindElement(By.Id("your_input_element_id"));

        // Get the current value of the input element
        string inputValue = inputElement.GetAttribute("value");

        // Print the value to the console
        Console.WriteLine("Current Value: " + inputValue);

        // Close the driver when done
        driver.Quit();
    }
}

Set the Value of an Input Element:

To set a new value to an input element, you can use the SendKeys method. Here’s an example:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

class Program
{
    static void Main(string[] args)
    {
        // Create a new instance of the Chrome driver
        IWebDriver driver = new ChromeDriver();

        // Navigate to your web page
        driver.Navigate().GoToUrl("your_website_url_here");

        // Find the input element by its ID (replace with your element's ID)
        IWebElement inputElement = driver.FindElement(By.Id("your_input_element_id"));

        // Set a new value to the input element
        inputElement.SendKeys("New Value");

        // Close the driver when done
        driver.Quit();
    }
}