Insert data

Insert Data

Add a new function to program class called write data has given below:

static void WriteData()
{
    try
    {
        using (SqlConnection connection = new SqlConnection(ConString))
        {
            //Create the SqlDataAdapter instance by specifying the command text and connection object
            var dataAdapter = new SqlDataAdapter("SELECT * FROM Student", connection);

            // At this point SqlCommandBuilder should generate T-SQL statements automatically
            var commandBuilder = new SqlCommandBuilder(dataAdapter);

            //Creating DataSet Object
            var dataSet = new DataSet();
            //Filling the DataSet using the Fill Method of SqlDataAdapter object
            dataAdapter.Fill(dataSet);

            //Now Update First Row i.e. Index Position 0
            var dataRow = dataSet.Tables[0].Rows[0];
            dataRow["Name"] = "Name Updated";

            //Provide the DataSet and the DataTable name to the Update method
            //Here, SqlCommandBuilder will automatically generate the UPDATE SQL Statement 
            var rowsUpdated = dataAdapter.Update(dataSet, dataSet.Tables[0].TableName);

            if (rowsUpdated == 0)
                Console.WriteLine("\nNo Rows Updated");
            else
                Console.WriteLine($"\n{rowsUpdated} Row(s) Updated");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("OOPs, something went wrong.\n" + e);
    }
}

Call the method

We should then call the newly created function from the main method, the modified code should be as shown below:

For more details you can visit the link below

Last updated