Results 1 to 4 of 4

Thread: Not sure how to call a function?

  1. #1
    PowerPoster
    Join Date
    Jan 04
    Posts
    3,616

    Not sure how to call a function?

    I am in the process of teaching myself the C# language and running into issues. As simple and ridiculous as this sounds I can't seem to call a function. I have created a class for all my DB function. Here is what it looks like:

    Code:
    using System;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace WindowsFormsApplication1
    {
        class DBUtilities
        {
            public SqlConnection dbConn()
            {
                SqlConnection cnn = new SqlConnection("Data Source=MCK\\MCKEXPRESS;Initial Catalog=myDataBase;Integrated Security=SSPI;");
    
                if (cnn == null && cnn.State == System.Data.ConnectionState.Open) 
                { 
                   cnn.Open();
                } 
    
                return cnn;
            }
        }
    }
    Now, I have a Windows Form in which I want to call the function dbConn() and I'm just not sure how to do it. I've tried googling it and not finding exactly what I'm looking for. Looking at the code above, if you know of a more efficient way to do this...I'm all ears!!!

    Thanks,
    Blake

  2. #2
    Lively Member
    Join Date
    Apr 10
    Location
    Australia
    Posts
    71

    Re: Not sure how to call a function?

    The DBUtilities class either needs to be instantiated, or the dbConn method needs to be declared as static. I'll let you research what's best for you.

    Currently, you need to do the following in your form to use the method.

    Code:
    DBUtilities utilities = new DBUtilities();
    SqlConnection connection = utilities.dbConn();
    Or, you can change the method to be static.

    Code:
    public static SqlConnection dbConn()
    {
    
    ...
    }
    Then in the form you can go
    Code:
    SqlConnection connection = DBUtilities.dbConn();

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    81,249

    Re: Not sure how to call a function?

    This is really no different to VB. If you were to define a class to contain all your data access code in VB then it would be exactly the same, i.e. instantiate the class or else declare the members Shared. If you were to use a module in VB then, as I'm sure you have heard, module variables are inherently Shared, so a module is simply a class with all Shared members.

  4. #4
    PowerPoster
    Join Date
    Jan 04
    Posts
    3,616

    Re: Not sure how to call a function?

    Thanks guys...
    Blake

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •