|
-
Aug 31st, 2012, 05:01 PM
#1
Thread Starter
PowerPoster
[RESOLVED] 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,
-
Aug 31st, 2012, 08:21 PM
#2
Re: Not sure how to call a function?
Since your class isn't static, you'll need to create an instance of it on your other form.
C# Code:
//create the instance DBUtilities dbutils = new DBUtilities(); //call the function SqlConnection con = dbutils.dbConn();
-
Aug 31st, 2012, 09:38 PM
#3
Re: Not sure how to call a function?
Why are you checking if cnn is null? Perhaps what you need to do is to instantiate cnn once and just open and close it accordingly. And you are also checking if its state is open then why are you opening it? Did you miss an exclamation point (!) there?
-
Sep 1st, 2012, 01:18 AM
#4
Thread Starter
PowerPoster
Re: Not sure how to call a function?
Thanks guys,
That helped. Not sure why that post code checks for connectionState.Open. In my code, it actually shows connectionState.Closed. I must have forgot to change it in the post.
-
Sep 1st, 2012, 06:26 AM
#5
Frenzied Member
Re: Not sure how to call a function?
even no need to check null value .the following is more simplified way .
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.State == System.Data.ConnectionState.Open)
{
cnn.Open();
}
return cnn;
}
}
}
-
Sep 1st, 2012, 11:49 AM
#6
Thread Starter
PowerPoster
Re: Not sure how to call a function?
I actually changed my code to that after I looked at it more. The way I had it before, I had found as an example in open a sqlConnection.
Thanks firoz.raj
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|