[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 509
  • Last Modified:

.NET C# , winform

I am trying to work with a sample ado.net example. I have taken helper class. here is the code
i have taken a form with a button to test connection and helper class. but when i run the program it is throwing error as: Object reference not set to an instance of an object.Nul reference expection was unhandled. what is the problem ?

form.cs( have taken a button) code for form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DbDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btntestConnection_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
           
            con.ConnectionString = Helper.ConnectionString;

            try
            {

                con.Open();
                MessageBox.Show("Success");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }


            finally
            {

                if (con.State == ConnectionState.Open)
                    con.Close();
            }
        }
    }
}

code for app.config is

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name=" MSNETDb"  connectionString="Server=.\sqlexpress; database=MSNETDemodb;Integrated security= true"/>
  </connectionStrings>
</configuration>

now have taken helperclass, helper.cs

here is the code for it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DbDemo
{
    class Helper
    {

        public static String ConnectionString
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["MSNETDb"].ConnectionString;
            }
        }
    }
}
but when i run it is throwing errror

what is the solution

0
coventri
Asked:
coventri
  • 11
  • 10
1 Solution
 
coventriAuthor Commented:
urgent
0
 
AshokCommented:
Use this function.....

    public static string GetConnectionString(string strConnection)
    {
      string strReturn = "";
      try
      {
        if (!string.IsNullOrEmpty(strConnection)) //a connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
        }
        else //no connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
        }
      }
      catch (Exception err)
      {
        Console.WriteLine("1 " + err.Message.ToString());
      }
      return strReturn;
    }

Call function like this.....

sConnStr = GetConnectionString("connUserProfile");

      conn = new SqlConnection(sConnStr);
      try
      {
        conn.Open();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }

HTH
Ashok
0
 
AshokCommented:
I forgot to mention this...

add

using System.Configuration;

HTH
Ashok
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
AshokCommented:
using System.Configuration;

.....

  public static string GetConnectionString(string strConnection)
    {
      string strReturn = "";
      try
      {
        if (!string.IsNullOrEmpty(strConnection)) //a connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
        }
        else //no connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
        }
      }
      catch (Exception err)
      {
        Console.WriteLine("1 " + err.Message.ToString());
      }
      return strReturn;
    }

Call function like this.....

sConnStr = GetConnectionString("MSNETDb");

      conn = new SqlConnection(sConnStr);
      try
      {
        conn.Open();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }

HTH
Ashok
0
 
AshokCommented:
Was this comment helpful? Yes No
ashok111:
using System.Configuration;

.....

  public static string GetConnectionString(string strConnection)
    {
      string strReturn = "";
      try
      {
        if (!string.IsNullOrEmpty(strConnection)) //a connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
        }
        else //no connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
        }
      }
      catch (Exception err)
      {
        Console.WriteLine("1 " + err.Message.ToString());
      }
      return strReturn;
    }

Call function like this.....

string sConnStr = GetConnectionString("MSNETDb");

      conn = new SqlConnection(sConnStr);
      try
      {
        conn.Open();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }

HTH
Ashok
0
 
coventriAuthor Commented:
could you please explain in the prosepctive of app.config file and helper class which i worked
0
 
coventriAuthor Commented:
here your connection name is same connection name in app.config right?
also i am getting error as  get connection string cannot be found
0
 
coventriAuthor Commented:
Error      1      The name 'GetConnectionString' does not exist in the current context      
0
 
joriszwaenepoelCommented:
On whet line of your code do you get that exception?
0
 
coventriAuthor Commented:
In the below line i got exeption , it is helper.cs class

   get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["MSNETDb"].ConnectionString;
            }
0
 
AshokCommented:
Error      1      The name 'GetConnectionString' does not exist in the current context

Make sure you add above function in .cs file which is in same namespace and
it is defined as

public static string GetConnectionString(string strConnection)

here your connection name is same connection name in app.config right?
Yes, in your case

<connectionStrings>
    <add name=" MSNETDb"  connectionString="Server=.\sqlexpress; database=MSNETDemodb;Integrated security= true"/>
  </connectionStrings>

so name is MSNETDb (BTW in above "connectionString", first letter is not capital)

Remember that C# is case-sensitive so I think it should be....

<connectionStrings>
    <add name=" MSNETDb"  ConnectionString="Server=.\sqlexpress; database=MSNETDemodb;Integrated security= true"/>
  </connectionStrings>

HTH
Ashok
0
 
coventriAuthor Commented:
hi ashok,
here is the code ,
i have taken new class1.cs  and here is the code  for that

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;

namespace DbDemo
{
    class Class1
    {

        public static string GetConnectionString(string strConnection)
        {
            string strReturn = "";
            try
            {
                if (!string.IsNullOrEmpty(strConnection)) //a connection string name was provided
                {
                    strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
                }
                else //no connection string name was provided
                {
                    strReturn = ConfigurationManager.ConnectionStrings["MSNETDb"].ConnectionString;
                }
            }
            catch (Exception err)
            {
                Console.WriteLine("1 " + err.Message.ToString());
            }
            return strReturn;
        }
    }
}


and now for app.config here is the code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name=" MSNETDb "  connectionString="Server=.\sqlexpress; database=MSNETDemodb;Integrated security= true"/>
  </connectionStrings>
</configuration>

and now for form1.cs

here is the code for button

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DbDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btntestConnection_Click(object sender, EventArgs e)
        {
           



            string sConnStr = GetConnectionString("MSNETDb");
            SqlConnection con = new SqlConnection();
            con = new SqlConnection(sConnStr);
            try
            {
                con.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
    }
}

even though i am getting error as  The name 'GetConnectionString' does not exist in the current context
0
 
AshokCommented:
Let me check something.  I will get back to you shortly.

Ashok
0
 
AshokCommented:
In app.config  (I was wrong about first letter capital in connectionString).

<connectionStrings>
    <add name="MSNETDb"
      connectionString="Server=.\sqlexpress;database=MSNETDemodb;Integrated security=true" />
</connectionStrings>

For now, can you put code of the function in Form1.cs file.  That is how I have it.
Once it works and if you need it to be outside we will figure it out.

HTH
Ashok
0
 
coventriAuthor Commented:
hi ashok,
yes i have put the code in form i.cs and is giving me as """ The connection string propert has not been intiliazed"
0
 
AshokCommented:
Your Form1.cs should look something like.....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DbDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    public static string GetConnectionString(string strConnection)
    {
      string strReturn = "";
      try
      {
        if (!string.IsNullOrEmpty(strConnection)) //a connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
        }
        else //no connection string name was provided
        {
          strReturn = ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
        }
      }
      catch (Exception err)
      {
        Console.WriteLine("1 " + err.Message.ToString());
      }
      return strReturn;
    }

     private void btntestConnection_Click(object sender, EventArgs e)
     {
            string sConnStr = GetConnectionString("MSNETDb");
            SqlConnection con = new SqlConnection();
            con = new SqlConnection(sConnStr);
            try
            {
                con.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
    }
}
0
 
AshokCommented:
If you already have the code as my previous post and getting error

i have put the code in form i.cs and is giving me as """ The connection string propert has not been intiliazed"

Can you post complete code of a class and specify exactly which line is causing error?

Ashok
0
 
coventriAuthor Commented:
yes it is same as the above one
0
 
coventriAuthor Commented:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DbDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static string GetConnectionString(string strConnection)
        {
            string strReturn = "";
            try
            {
                if (!string.IsNullOrEmpty(strConnection)) //a connection string name was provided
                {
                    strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
                }
                else //no connection string name was provided
                {
                    strReturn = ConfigurationManager.ConnectionStrings["MSNETDb"].ConnectionString;
                }
            }
            catch (Exception err)
            {
                Console.WriteLine("1 " + err.Message.ToString());
            }
            return strReturn;
        }

        private void btntestConnection_Click(object sender, EventArgs e)
        {
            string sConnStr = GetConnectionString("MSNETDb");
            SqlConnection con = new SqlConnection();
            con = new SqlConnection(sConnStr);
            try
            {
                con.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
0
 
AshokCommented:
In that case, it looks like there is some problem with App.config.

Delete App.config from solution.

Then goto Solution Explorer and "Add New Item"
Select Application Configuration File

That will automatically add "App.config" with

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

Now change it to

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
    <add name="MSNETDb"
      connectionString="Server=.\sqlexpress;database=MSNETDemodb;Integrated security=true" />
</connectionStrings>
</configuration>

I think above is complete and correct.

HTH
Ashok


0
 
coventriAuthor Commented:
thanks for yout time and accurate solution
0
 
AshokCommented:
That's good.  I am glad to help you.

Ashok
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 11
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now