logo for asktheoracle.net
Home
What's new?
Oracle Tutorials
PL/SQL
SQL
Oracle Tips & Tricks
Advanced Tutorials
Certification
Oracle 10g
Oracle 11g
Oracle and .Net
Oracle Tools
Disclaimer
Privacy Policy
Search This Site
Oracle Questions?
leftimage for asktheoracle.net

How To Build a WinForms.NET Application With Oracle

This tutorial on using Oracle with Visual Studio WinForms.NET covers the basics of database access and data manipulation from C#. Security considerations (whilst important) are beyond the scope of this tutorial.

Prerequisites

  1. Install Visual Studio 2008 for building your application
  2. Install 10g XE. Make sure that you follow the instructions to enable the HR database. If you accepted the default settings of the installer, 
 the server is in c:\oraclexe. The listener.ora, sqlnet.ora and tnsnames.ora files are in c:\oraclexe\app\oracle\product\10.2.0\server\NETWORK\ADMIN.
3. Start the database (Start -> All Programs -> 10g Express Edition -> Start Database)
4. Install 11g Data Access Components (ODAC) for Visual Studio 11.1.07.20 or later. If you accepted the default settings of the installer the ODAC is installed in c:\app.
6. Copy the following files: listener.ora, sqlnet.ora and tnsnames.ora to c:\app\product\11.1.0\client_1\Network\Admin to enable the application to connect to the database and to prevent a TNS-12514: TNS: could not resolve the connect identifier error.

Create your WinForms.NET project


Watch the above video and learn in just a few minutes how to build your application and link it to a database.
  1. Start Visual Studio 2008 (Start -> All Programs -> Microsoft Visual Studio 2008)
  2. Select File->New Project from the Visual Studio menu
  3. Select the “Windows Forms Applications”  template in the New Projects dialog box and name your application “OracleWinFormsApp1”. Accept the defaults click “OK”.

    Visual Studio - new project

  4. The next step is to add a reference to the ODP.NET Provider DLL. To do this, right click on your new project "OracleWinFormsApp1”,  and select “Add Reference…”. Your screen should look like this:

    VS2008 winforms add dll

  5. Select “Oracle.DataAccess” on the .NET tab of  the list that appears (ODP.NET is part of this component).

    Visual Studio 2008 oracle data access
  6. Oracle Tips & Tricks
    to SKYROCKET Your Career!

    If you're not already a subscriber to our newsletter you're missing out on a myriad of tips and tricks you need to become a better, faster, smarter developer. Subscribe now and ignite your career.

  7. Click the “OK” button to add it as a reference to the project and the Oracle.DataAccess icon should be displayed under the References tree
    Visual Studio 2008 Oracle.DataAccess
  8. Next add a button and label control from the Toolbox to the top half of the Windows Form

    Visual Studio 2008 button toolbox
  9. Double click on the “button1” icon on the form so you can add code to invoke the sample HR database in the button click event handler.

    Visual Studio 2008 invoking sample hr database

  10. Add the following lines of code to the event handler (entitled button1_Click)

    string oracledb =
    "Data Source=(DESCRIPTION=(ADDRESS_LIST="
    + "(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))"
    + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));"
    + "User Id=HR;Password=HR;";

    OracleConnection connection =
    new OracleConnection(oracledb);

    connection.Open();
    OracleCommand command = new OracleCommand();
    command.Connection = connection;
    command.CommandText =
    "SELECT department_name FROM departments WHERE department_id = 10";

    command.CommandType = CommandType.Text;

    OracleDataReader dataReader = command.ExecuteReader();
    dataReader.Read();

    label1.Text = dataReader["department_name"].ToString();

    dataReader.Dispose();
    command.Dispose();
    connection.Dispose();


    We also need to add the following declaration to the set of using declarations at the beginning of the form module:

    using Oracle.DataAccess.Client; 

  11. Run the form to test it and you should see something like the following

    Visual Studio 2008 test results
  12. At the moment the department id is hard coded in the query, which means we'll always display the name of department 10. 
    To allow the user to enter the department id we need to add a text box. To do this, click on the “Toolbox” and add another label control and a text box control to your form. Name the label “Please enter a Department ID:”. Your form should resemble the following:

  13. Visual Studio 2008 adding text box

    We also need to change the select statement to use the department id entered by the user as follows:

    command.CommandText =
    "select department_name from departments where department_id = "
    + textBox1.Text;


  14. Now we can run our application and test it by entering a value of “10” for the department id. The result should look like this:

    Visual Studio 2008 - results of Oracle query

  15. The next thing to do is to add some error handling in case a non existent department id is entered. To do this we need to check the result of the data read operation on the database. If nothing is returned we display a user-friendly error message, otherwise we display the department name, like so:

    if (dataReader.Read()) { label1.Text = dataReader["department_name"].ToString(); } else { label1.Text = "department id not found"; } 

  16. Now if we re-run the application and enter a value of “500” we should see something like this:

    Visual Studio 2008: specified dept id not found

  17. We could make this application much more useful by retrieving multiple rows and colums but we'll leave that for the advanced tutorial!

    One thing we probably should do though is to improve the error handling to capture exceptions and other errors.

    This is done by using the try-catch-finally block. Modifying the event handler to do this should give us something like the following:

    private void button1_Click(object sender, EventArgs e)
    {
    string oracledb = "Data Source=(DESCRIPTION=(ADDRESS_LIST="
    + "(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))"
    + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)))"
    + "User Id=HR;Password=HR;";

    OracleConnection connection = null;
    OracleCommand command = null;
    OracleDataReader dataReader = null;

    try
    {
    connection = new OracleConnection(oracledb);
    connection.Open();

    command = new OracleCommand();
    command.Connection = connection;
    command.CommandText =
    "select department_id, department_name, location_id “
    + “from departments";
    command.CommandType = CommandType.Text;

    dataReader = command.ExecuteReader();

    if (dataReader.Read()) { label1.Text = dataReader["department_name"].ToString(); } else { label1.Text = "department id not found"; } 
    }

    catch (OracleException oe)
    //Catch database specific errors
    {
    if (12545 == oe.Number)
    {
        MessageBox.Show("The database is not available.");
    }
    else if (12514 == oe.Number)
    {
        MessageBox.Show("Unable to connect to the database");
    }
    else
    {
        MessageBox.Show("database error: "+ oe.Message.ToString());
    }
    }
    catch (Exception ex)
    //while this catches everything else
    {
    MessageBox.Show(ex.Message.ToString());
    }

    finally
    {
        if (null != dataReader)
        {
            dataReader.Dispose();
        }
        if (null != command)
        {
            command.Dispose();
        }
        if (null != connection)
        {
            connection.Dispose();
        }
    }
    }
  18. Now let's test this new code by stopping the database and re-running our application. We should see the following message displayed:

    Visual Studio 2008 dialog box
If you're looking for more training, with our partners we offer expert instructor-led training in New Zealand and in the UK. Learn quickly and easily from their highly experienced consultants who have skills honed over many years spent designing, building and testing real-world systems.