none
linq only updating one row RRS feed

  • Question

  • I am coding and testing on a C#. net 2010 application where I am working on linq to sql. I am trying to add one to lots of rows in a table based upon what a user selects in a group of checkboxes. When I run either code,  only the last row is added to the sql server 2008 r2. Can you tell me what I can do so all rows that have been selected get updated to the table?


    attDataContext attPlanDataContext = new AttDataContext();
    Attestation_Plan attplan = null;
    attplan = new Attestation_Plan();

    for (int i = 0; i < ChkBoxLstPlan.Items.Count; i++)
    {
    if (ChkBoxLstPlan.Items[i].Selected)
    {
    attplan.Attestation_id = att.Attestation_id;
    attplan.HNumber = ChkBoxLstPlan.Items[i].Value.Substring(0, 5);
    attPlanDataContext.Attestation_Plans.InsertOnSubmit(attplan);
     }
    }

    attPlanDataContext.SubmitChanges();

     

     

     

     

    Monday, October 31, 2011 4:50 PM

Answers

  • Wendy,

    You need to instantiate a new attplan during each loop, otherwise it will insert the same one.  So try this code change:

    attDataContext attPlanDataContext = new AttDataContext();
    Attestation_Plan attplan = null;
    attplan = new Attestation_Plan();
    
    for (int i = 0; i < ChkBoxLstPlan.Items.Count; i++)
    {
    if (ChkBoxLstPlan.Items[i].Selected)
    {
    attplan = new Attestation_Plan();
    attplan.Attestation_id = att.Attestation_id;
    attplan.HNumber = ChkBoxLstPlan.Items[i].Value.Substring(0, 5);
    attPlanDataContext.Attestation_Plans.InsertOnSubmit(attplan);
     }
    }
    
    attPlanDataContext.SubmitChanges();
    
    
    

     


    Tom Overton
    Monday, October 31, 2011 5:08 PM

All replies

  • Wendy,

    You need to instantiate a new attplan during each loop, otherwise it will insert the same one.  So try this code change:

    attDataContext attPlanDataContext = new AttDataContext();
    Attestation_Plan attplan = null;
    attplan = new Attestation_Plan();
    
    for (int i = 0; i < ChkBoxLstPlan.Items.Count; i++)
    {
    if (ChkBoxLstPlan.Items[i].Selected)
    {
    attplan = new Attestation_Plan();
    attplan.Attestation_id = att.Attestation_id;
    attplan.HNumber = ChkBoxLstPlan.Items[i].Value.Substring(0, 5);
    attPlanDataContext.Attestation_Plans.InsertOnSubmit(attplan);
     }
    }
    
    attPlanDataContext.SubmitChanges();
    
    
    

     


    Tom Overton
    Monday, October 31, 2011 5:08 PM
  • Thanks for the reply.
    Thursday, February 23, 2012 11:19 PM