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,
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();
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.
Re: Not sure how to call a function?