0

I trying to change database from MySQL to SQL server 2008 express for this VS2010 C# project. However after i change the connection string and queries, the program produces error 'null reference exception was unhandled' on the "cmr.close()". Here is the code and the place where the error occurred :

namespace JawiRdrSQL
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SqlConnection sc = new SqlConnection("Data Source=USER-PC\\SQLEXPRESS;Initial Catalog=firstDB;Integrated Security=True");
        SqlCommand cmd;
        SqlDataReader cmr;
        public MainWindow()
        {
            InitializeComponent();
        }


        //string sc;
        string strValue;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            strValue = textBox1.Text;


             char[] strVal = strValue.ToCharArray();
             Array.Reverse(strVal);

            foreach(char obj in strVal)
            {
                try
                {
                   sc.Open();
                    cmd = new SqlCommand ("select JawiReader (stringR)" + ((char)obj), sc);
                    cmd.ExecuteNonQuery();

                    if (cmr.Read())
                    {
                        label1.Content += cmr["stringJ"].ToString();

                    }
                    else
                    {
                        MessageBox.Show("tidak sah");
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                cmr.Close(); // error occurs here
                sc.Close();
            }
        }

I am trying to produce a program that received a string which will be break into char and then compared to values in database. After that the program will output a string of values from the database.

James Z
  • 11,838
  • 10
  • 25
  • 41
jenan
  • 9
  • 4
  • 1
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Hamid Pourjam Jun 14 '15 at 12:20
  • if(cmr != null)cmr.Close(); The is no need to open and close the connetion for each command. Move the connection 'sc' open/close outside the foreach loop. – jdweng Jun 14 '15 at 12:34

2 Answers2

2

Since you define it as;

SqlDataReader cmr;

it will be null by default. That's why you get NullReferenceException when you try to call;

cmr.Close();

because you never initialize your reader. You don't need to use ExecuteNonQuery for that case. Just generate your cmr with ExecuteReader method like;

cmd = new SqlCommand ("select JawiReader (stringR)" + ((char)obj), sc);
cmr = cmd.ExecuteReader();

And please use using statement to dispose your connections, commands and reader.

Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
  • thanks for the help. The error is gone now, however the program still have another error which is "an expression of non-boolean type specified in the context where a condition is expected, near stringr" – jenan Jun 15 '15 at 11:58
  • @jenan Are you sure your query is correct? Did you try it on management studio? – Soner Gönül Jun 15 '15 at 11:59
  • hi, sorry to ask you another question, but I already reach my limit for asking questions. I got a problem in displaying the sql content on my label. its suppose to display an array of char, so far I got an alert prompt saying "invalid column name on last char", do you know whats the problem is? – jenan Jun 16 '15 at 14:19
0

You never initialize your SQLDataReader cmr;

Therefore, of course you get an error when you want to close it.

You cannot close an object which has not been created at all.

[I want to close the door of my castle, but unfortuntaley, this castle exists only in my dream ...]

SQL Police
  • 3,679
  • 1
  • 18
  • 47