Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
4.40/5 (6 votes)
See more:
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;

C#
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 ;

C#
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
Comments
ZurdoDev 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.
Onur ERYILMAZ 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 ;)
[no name] 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.
Onur ERYILMAZ 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...
Onur ERYILMAZ 10-Jul-13 17:24pm    
i reach DbConnection but i get error message again :(

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
 
Share this answer
 
Comments
Onur ERYILMAZ 10-Jul-13 16:56pm    
Thank you again...
Sergey Alexandrovich Kryukov 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 10-Jul-13 18:04pm    
Well answered :-D
Sergey Alexandrovich Kryukov 10-Jul-13 18:18pm    
Thank you, Espen.
—SA
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
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 10-Jul-13 16:44pm    
Good point, a 5.
—SA
Espen Harlinn 10-Jul-13 16:50pm    
Thank you :-D
Onur ERYILMAZ 10-Jul-13 16:56pm    
Thamk you for your comment...
Sergey Alexandrovich Kryukov 10-Jul-13 17:05pm    
I would suggest you accept this advice formally (green button); it should be useful for you.
—SA
C#
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()
 
Share this answer
 
Comments
a.tafese 14-May-15 8:41am    
if (FAXNO != "")
{
//FAXNO = Convert.ToInt32(textBox3.
int response = 0;
FAXCOMLib.FaxServer faxServer = new FAXCOMLib.FaxServerClass();
try
{
faxServer.Connect("FAXSERVER");
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
FAXCOMLib.FaxDoc faxDoc = (FAXCOMLib.FaxDoc)faxServer.CreateDocument(FileName);
try
{
faxDoc.FaxNumber = FAXNO;
faxDoc.RecipientName = TO;
faxDoc.DisplayName = DocmentName;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
try
{
response = faxDoc.Send();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
try
{
faxServer.Disconnect();
}
catch (Exception Ex)
{

MessageBox.Show(Ex.Message);
}

}
}
a.tafese 14-May-15 8:43am    
if (FAXNO != "")
{
//FAXNO = Convert.ToInt32(textBox3.
int response = 0;
FAXCOMLib.FaxServer faxServer = new FAXCOMLib.FaxServerClass();
try
{
faxServer.Connect("FAXSERVER");
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
FAXCOMLib.FaxDoc faxDoc = (FAXCOMLib.FaxDoc)faxServer.CreateDocument(FileName);
try
{
faxDoc.FaxNumber = FAXNO;
faxDoc.RecipientName = TO;
faxDoc.DisplayName = DocmentName;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
try
{
response = faxDoc.Send();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
try
{
faxServer.Disconnect();
}
catch (Exception Ex)
{

MessageBox.Show(Ex.Message);
}

}
}


how to solve Object reference not set to an instance of an object. exception

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900