Click here to Skip to main content
15,922,696 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
If the textbox_deli is empty it could just insert the fruit and vegtables in the database, and if there is something in textbox_deli it could insert all things in the database.

It do that, but there is comming and error when its finish.

What am I doing wrong??

Object reference not set to an instance of an object.

XML
Line 140:         List<ValgtFrugt> valgteFrugter = (List<ValgtFrugt>)Session["ValgteFrugter"];
Line 141:
Line 142:            var dataTable = new DataTable(Session["ValgteFrugter"].ToString());
Line 143:
Line 144:


My backend code:

C#
protected void Button_putikurv_Click(object sender, EventArgs e)
   {

       int totalvaerdi = 0;

       List<ValgtDeli> valgteDeli = new List<ValgtDeli>(); //Her laver jeg en liste over valgte frugter. Det er et nyt objekt, som kan indeholde påde ID, Navn, Antal og Værdi

       foreach (DataListItem itm in VisDeli.Items)
       {
           if (itm.ItemType == ListItemType.Item || itm.ItemType == ListItemType.AlternatingItem)
           {
                   TextBox TextBox_deli = itm.FindControl("TextBox_deli") as TextBox;

               string DeliNavn = TextBox_deli.Attributes["DeliNavn"]; //Det her skal vel være en streng!?

               int deliID = Convert.ToInt32(TextBox_deli.Attributes["ID"]);

               if (TextBox_deli.Text != null)
               {

                   if (string.IsNullOrEmpty(TextBox_deli.Text))
                   {
                       TextBox_deli.Text = "0";

                   }
               }

               int enkeltDeliAntal = int.Parse(TextBox_deli.Text);

               totalvaerdi += (enkeltDeliAntal);

               if (enkeltDeliAntal > 0)
               {
                   ValgtDeli frugtenDerskalTilfoejes = new ValgtDeli(); //Opret frugten og angiv værdier
                   frugtenDerskalTilfoejes.ID = deliID;
                   frugtenDerskalTilfoejes.Navn = DeliNavn;
                   frugtenDerskalTilfoejes.Antal = enkeltDeliAntal;
                   valgteDeli.Add(frugtenDerskalTilfoejes);

               }

           }
           if (totalvaerdi > 0)
           {
               Session["ValgteDeli"] = valgteDeli;
               opretOrdre();
           }
           else
           {
               opretOrdre();
           }


       }


   }
   private void opretOrdre()
   {

       if (Session["ValgteDeli"] == null )
       {

           SqlConnection conn = new SqlConnection();
           conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

           SqlCommand cmd = new SqlCommand();
           cmd.Connection = conn;
           cmd.CommandText = "INSERT INTO ordre (dato, navn, efternavn, mobil, adresse, mail, postnr, bynavn) VALUES(GETDATE(), @navn, @efternavn, @mobil, @adresse, @mail, @postnr, @bynavn); SELECT SCOPE_IDENTITY()";

           cmd.Parameters.Add("@navn", SqlDbType.VarChar).Value = TextBox_navn.Text;
           cmd.Parameters.Add("@efternavn", SqlDbType.VarChar).Value = TextBox_efternavn.Text;
           cmd.Parameters.Add("@mobil", SqlDbType.VarChar).Value = TextBox_mobil.Text;
           cmd.Parameters.Add("@adresse", SqlDbType.VarChar).Value = TextBox_adresse.Text;
           cmd.Parameters.Add("@mail", SqlDbType.VarChar).Value = TextBox_mail.Text;
           cmd.Parameters.Add("@postnr", SqlDbType.VarChar).Value = TextBox_postnr.Text;
           cmd.Parameters.Add("@bynavn", SqlDbType.VarChar).Value = TextBox_by.Text;


           conn.Open();
           object orderId = cmd.ExecuteScalar();
           conn.Close();

           //SÅ skal vi bruge de parametre der skal til for at kunne skrive til vore OrdrerLinier Tabel
           //Og evt. opdatere vores produkts lagerbeholdning
           //########################//
           //SÅ til vores ordrerlinier
           //fk_ordre - den fra object'et
           cmd.Parameters.Add("@fk_ordre", SqlDbType.Int).Value = orderId;
           //fk_produktId - fra session _kurv. Sættes nu til 0, den den skal ind i foreach løkken og få sin værdi.
           //cmd.Parameters.Add("@prod", SqlDbType.Int).Value = 0;

           //Produkt antal - sammen som Id'et. Sættes til 0 og får værdi i løkken
           cmd.Parameters.Add("@Antal", SqlDbType.Int).Value = 0;


        List<ValgtFrugt> valgteFrugter = (List<ValgtFrugt>)Session["ValgteFrugter"];

           var dataTable = new DataTable(Session["ValgteFrugter"].ToString());



           dataTable.Columns.Add("ID", typeof(int));
           dataTable.Columns.Add("Navn", typeof(string));
           dataTable.Columns.Add("Antal", typeof(int));
           dataTable.Columns.Add("Vaerdi", typeof(int));

           foreach (ValgtFrugt frugt in valgteFrugter)
           {
               dataTable.Rows.Add(frugt.ID, frugt.Navn, frugt.Antal, frugt.Vaerdi);
           }

           List<ValgtGroent> valgteGroent = (List<ValgtGroent>)Session["ValgteGroent"];
           var dataTable1 = new DataTable(Session["ValgteGroent"].ToString());

           dataTable1.Columns.Add("ID", typeof(int));
           dataTable1.Columns.Add("Navn", typeof(string));
           dataTable1.Columns.Add("Antal", typeof(int));
           dataTable1.Columns.Add("Vaerdi", typeof(int));

           foreach (ValgtGroent groent in valgteGroent)
           {
               dataTable1.Rows.Add(groent.ID, groent.Navn, groent.Antal, groent.Vaerdi);
           }



           DataTable dtAll = new DataTable();
           dtAll = dataTable.Copy();
           dtAll.Merge(dataTable1, true);



           conn.Open();

           foreach (DataRow row in dtAll.Rows)
           {
               cmd.CommandText = @"INSERT INTO ordre_linie
                               (fk_ordre_id, antal, navn)
                               VALUES (@fk_ordre, @Antal, @navn)";



               cmd.Parameters["@Antal"].Value = row["Antal"];
               cmd.Parameters["@navn"].Value = row["Navn"];


               cmd.ExecuteNonQuery();
           }

           conn.Close();
           Session.Abandon();

           Session.Contents.RemoveAll();
           Label_tak.Text = "Tak for henvendelsen, ordren bliver behandlet hurtigst muligt";

       }
       else
       {


           SqlConnection conn = new SqlConnection();
           conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

           SqlCommand cmd = new SqlCommand();
           cmd.Connection = conn;
           cmd.CommandText = "INSERT INTO ordre (dato, navn, efternavn, mobil, adresse, mail, postnr, bynavn) VALUES(GETDATE(), @navn, @efternavn, @mobil, @adresse, @mail, @postnr, @bynavn); SELECT SCOPE_IDENTITY()";

           cmd.Parameters.Add("@navn", SqlDbType.VarChar).Value = TextBox_navn.Text;
           cmd.Parameters.Add("@efternavn", SqlDbType.VarChar).Value = TextBox_efternavn.Text;
           cmd.Parameters.Add("@mobil", SqlDbType.VarChar).Value = TextBox_mobil.Text;
           cmd.Parameters.Add("@adresse", SqlDbType.VarChar).Value = TextBox_adresse.Text;
           cmd.Parameters.Add("@mail", SqlDbType.VarChar).Value = TextBox_mail.Text;
           cmd.Parameters.Add("@postnr", SqlDbType.VarChar).Value = TextBox_postnr.Text;
           cmd.Parameters.Add("@bynavn", SqlDbType.VarChar).Value = TextBox_by.Text;


           conn.Open();
           object orderId = cmd.ExecuteScalar();
           conn.Close();

           //SÅ skal vi bruge de parametre der skal til for at kunne skrive til vore OrdrerLinier Tabel
           //Og evt. opdatere vores produkts lagerbeholdning
           //########################//
           //SÅ til vores ordrerlinier
           //fk_ordre - den fra object'et
           cmd.Parameters.Add("@fk_ordre", SqlDbType.Int).Value = orderId;
           //fk_produktId - fra session _kurv. Sættes nu til 0, den den skal ind i foreach løkken og få sin værdi.
           //cmd.Parameters.Add("@prod", SqlDbType.Int).Value = 0;

           //Produkt antal - sammen som Id'et. Sættes til 0 og får værdi i løkken
           cmd.Parameters.Add("@Antal", SqlDbType.Int).Value = 0;



           List<ValgtFrugt> valgteFrugter = (List<ValgtFrugt>)Session["ValgteFrugter"];

           var dataTable = new DataTable(Session["ValgteFrugter"].ToString());



           dataTable.Columns.Add("ID", typeof(int));
           dataTable.Columns.Add("Navn", typeof(string));
           dataTable.Columns.Add("Antal", typeof(int));
           dataTable.Columns.Add("Vaerdi", typeof(int));

           foreach (ValgtFrugt frugt in valgteFrugter)
           {
               dataTable.Rows.Add(frugt.ID, frugt.Navn, frugt.Antal, frugt.Vaerdi);
           }

           List<ValgtGroent> valgteGroent = (List<ValgtGroent>)Session["ValgteGroent"];
           var dataTable1 = new DataTable(Session["ValgteGroent"].ToString());

           dataTable1.Columns.Add("ID", typeof(int));
           dataTable1.Columns.Add("Navn", typeof(string));
           dataTable1.Columns.Add("Antal", typeof(int));
           dataTable1.Columns.Add("Vaerdi", typeof(int));

           foreach (ValgtGroent groent in valgteGroent)
           {
               dataTable1.Rows.Add(groent.ID, groent.Navn, groent.Antal, groent.Vaerdi);
           }

           List<ValgtDeli> valgteDeli = (List<ValgtDeli>)Session["ValgteDeli"];


           var dataTable2 = new DataTable(Session["ValgteDeli"].ToString());

           dataTable2.Columns.Add("ID", typeof(int));
           dataTable2.Columns.Add("Navn", typeof(string));
           dataTable2.Columns.Add("Antal", typeof(int));

           foreach (ValgtDeli delikatesse in valgteDeli)
           {
               dataTable2.Rows.Add(delikatesse.ID, delikatesse.Navn, delikatesse.Antal);
           }

           DataTable dtAll = new DataTable();
           dtAll = dataTable.Copy();
           dtAll.Merge(dataTable1, true);
           dtAll.Merge(dataTable2, true);

           conn.Open();

           foreach (DataRow row in dtAll.Rows)
           {
               cmd.CommandText = @"INSERT INTO ordre_linie
                               (fk_ordre_id, antal, navn)
                               VALUES (@fk_ordre, @Antal, @navn)";



               cmd.Parameters["@Antal"].Value = row["Antal"];
               cmd.Parameters["@navn"].Value = row["Navn"];


               cmd.ExecuteNonQuery();
           }

           conn.Close();
           Session.Abandon();

           Session.Contents.RemoveAll();
           Label_tak.Text = "Tak for henvendelsen, ordren bliver behandlet hurtigst muligt uden deli";
       }




   }


/Tina
Posted
Comments
Kenneth Haugland 19-Oct-13 13:35pm    
Lisen here TuttiFrutti, this error normaly comes when you have forgotten to say something like:
List (frukter) = new List(frukter)();
tina_overgaard 19-Oct-13 13:44pm    
But were could it be??

There is coming a red line underneath when I put in the code near the list I already have
Kenneth Haugland 19-Oct-13 14:03pm    
I cant see it inisialized anywere, what you have done in the line:
List valgteFrugter = (List)Session["ValgteFrugter"];
is to direct cast the Session to a List of Frukter, so put a breakpoint below this and see if it is populated?
tina_overgaard 19-Oct-13 14:40pm    
I get the information correctly.
But it could just get the information from the session am I right?
Maybee like this or:
var dataTable = new DataTable(Session["ValgteFrugter"].ToString());

dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Navn", typeof(string));
dataTable.Columns.Add("Antal", typeof(int));
dataTable.Columns.Add("Vaerdi", typeof(int));

foreach (DataTable frugt in Session["ValgteFrugter"].ToString())
{
dataTable.Rows.Add(frugt.ID, frugt.Navn, frugt.Antal, frugt.Vaerdi);
}
tina_overgaard 19-Oct-13 14:41pm    
I already have the make this list, so it could not be there?

1 solution

Most typical reason for this exception is: Session["ValgteFrugter"] returns null. You did not find out what exactly was null. You really need to learn appropriate debugging technique to solve such problems by yourself. You cannot ask someone to help each time you face such kind of bugs.

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
tina_overgaard 20-Oct-13 7:23am    
Sorry for that, but I am á newbie to codeing. So this is the reason why I write so much, because I need som guidence. And trust me before I write I have sit with the code for hours before I have written on this forum. And sometimesit is probaly á dumb question for you guys, but to be better I need to ask and I actually learn something about it
Sergey Alexandrovich Kryukov 20-Oct-13 20:45pm    
There is nothing wrong with being a novice and asking many questions, especially if regular and persistent work goes behind then. That's why I try to give answers with teach a novice to solve problems, instead of fixing one immediate bug...

Good luck, call again.
—SA

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