Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: SQL .NET database
i have a little problem in my code, i tried to match my textbox value to database, bu i get an error message ...
 
here is my codes:
 
my main code;
 
 protected void btnAddNewTopic_Click(object sender, EventArgs e)
    {
        if (txtbAddNewTopic.Text == "")
        {
            MessageBox.Show("Please write topic!");
        }
        else if (goodob.Businness_Layer.AddNewTopic.NewTopicCheckSystem(txtbAddNewTopic.Text) == null)
        {
            MessageBox.Show("Your added topic is already in site!");
        }
        else
        {
            goodob.Businness_Layer.CreateNewTopic.crnewtopic(txtbAddNewTopic.Text);
            MessageBox.Show("Your topic has successfully created!");
        }
 

 
    }
 
and my check code ;
 
public static goodob.Businness_Layer.AddNewTopic NewTopicCheckSystem(string topic)
    {
        goodob.Businness_Layer.AddNewTopic xyz = null;
 
        string query = @"SELECT [topic_name] 
                       FROM topic
                       WHERE topic_name = @topic";
 
        goodob.Class1 connection1 = new goodob.Class1();
        connection1.sqlcommand.CommandText = query;
 
        SqlParameter topicparam = new SqlParameter("@topic_name", SqlDbType.VarChar);
        topicparam.Value = topic;
 
        connection1.sqlcommand.Parameters.Add(topic);
 
        System.Data.SqlClient.SqlDataReader reader = connection1.sqlcommand.ExecuteReader();
 
        if (!reader.HasRows)
        {
            connection1.close_connection();
            return null;
        }
 

 

        return xyz;
    }
 
i get an error in connection1.sqlcommand.CommandText = query; please help me!
Posted 10-Jul-13 10:46am
Comments
ryanb31 at 10-Jul-13 15:51pm
   
You'll have to step int your business logic layer and see what is happening. It looks like connection1.sqlcommand is not initialized.
Member 9048765 at 10-Jul-13 16:55pm
   
public class Class1
{
public System.Data.SqlClient.SqlConnection connection;
public System.Data.SqlClient.SqlCommand sqlcommand;
 
public void DbConnection(){
string connectionSql = "Server=ONUR\\SQLEXPRESS;Database=goodorbad;Trusted_Connection=True;";
 
connection = new SqlConnection(connectionSql);
 
sqlcommand = new SqlCommand();
 
sqlcommand.Connection = connection;
connection.Open();
}
public void close_connection(){
connection.Close();
}

}
 
this is my connection class is there wrong statement in here ... Thank you for comment btw ;)
ThePhantomUpvoter at 10-Jul-13 17:02pm
   
You are instantiating your class, "goodob.Class1 connection1 = new goodob.Class1();" but you are not calling the "DbConnection" method in your class to instantiate the connection or the command object and so they are going to be null when you try and use them.
Member 9048765 at 10-Jul-13 17:12pm
   
Yes i saw this now , when i debug but i cant reach DbConnection method... Normally i can use this in my Businesslayer , goodob.sqlconnectionlayer.class1.DbConnection bu unfortunately i can't reach...
Member 9048765 at 10-Jul-13 17:24pm
   
i reach DbConnection but i get error message again :(
ThePhantomUpvoter at 10-Jul-13 17:58pm
   
And that error message is what?
Member 9048765 at 11-Jul-13 10:26am
   
Object reference not set to an instance of an object error
ThePhantomUpvoter at 11-Jul-13 10:38am
   
Well you are just going to have to debug your code. I can't read your mind to know where you are getting that error from.
Member 9048765 at 11-Jul-13 13:14pm
   
i get an error in connection1.sqlcommand.CommandText = query;
Member 9048765 at 10-Jul-13 16:55pm
   
Thank you for your solution...
Member 9048765 at 10-Jul-13 16:59pm
   
And i forgot to write an error message...
 
Here : Object reference not set to an instance of an object.
Member 9048765 at 10-Jul-13 17:07pm
   
I debug my code putting breakpoints and i saw my connection1 and my query is return null , is this my problem or what can i do?
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

As ryanb31 suggested, connection1.sqlcommand could be null, another possibility is connection1 to be null.
 
Too bad you did not collect and share this information. Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.
 
Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].
 
Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].
 
The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].
 
Good luck,
—SA
  Permalink  
Comments
Member 9048765 at 10-Jul-13 16:56pm
   
Thank you again...
Sergey Alexandrovich Kryukov at 10-Jul-13 17:04pm
   
Sure. Will you accept the answer formally (green button)? This is what you really need to do.
—SA
Espen Harlinn at 10-Jul-13 18:04pm
   
Well answered :-D
Sergey Alexandrovich Kryukov at 10-Jul-13 18:18pm
   
Thank you, Espen.
—SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

The following outlines how you would usually work with SqlConnection, SqlCommand and SqlDataReader:
using System.Data.SqlClient;
namespace nn
{
    class Test
    {
        public void DoDbAction()
        {
            SqlConnection connection = new SqlConnection();
            using (connection)
            {
                connection.ConnectionString = GetConnectionString();
                connection.Open();
 
                SqlCommand command = connection.CreateCommand();
                using (command)
                {
                    command.CommandText = "SELECT ID,NAME FROM TEST";
                    SqlDataReader reader = command.ExecuteReader();
                    using (reader)
                    {
                        if (reader.Read())
                        {
                            int id = reader.GetInt32(0);
                            string name = reader.GetString(1);
                        }
                    }
                }
 
            }
        }
    }
}
 
Best regards
Espen Harlinn
  Permalink  
Comments
Sergey Alexandrovich Kryukov at 10-Jul-13 16:44pm
   
Good point, a 5.
—SA
Espen Harlinn at 10-Jul-13 16:50pm
   
Thank you :-D
Member 9048765 at 10-Jul-13 16:56pm
   
Thamk you for your comment...
Sergey Alexandrovich Kryukov at 10-Jul-13 17:05pm
   
I would suggest you accept this advice formally (green button); it should be useful for you.
—SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

goodob.Businness_Layer.AddNewTopic xyz = null;
           
           
            
            string query = @"SELECT [topic_name] 
                       FROM topic
                       WHERE topic_name = @topic";
 

            goodob.DAL.DBConn connection1 = new DAL.DBConn();
            connection1.DbConnection();
            connection1.sqlcommand.Parameters.AddWithValue("@topic", topic);
            connection1.sqlcommand.CommandText = query;
 
            
 
            SqlDataReader reader =connection1.sqlcommand.ExecuteReader();
 
            if (!reader.HasRows)
            {
                connection1.close_connection();
                return null;
            }
 
            connection1.close_connection();
            return xyz;
 
I change Class1 to DAL.DBConn and i add connection1.DbConnection()
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 280
1 Sergey Alexandrovich Kryukov 279
2 CPallini 205
3 Maciej Los 197
4 Afzaal Ahmad Zeeshan 160
0 OriginalGriff 5,635
1 DamithSL 4,496
2 Maciej Los 3,942
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,180


Advertise | Privacy | Mobile
Web01 | 2.8.141216.1 | Last Updated 12 Jul 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100