2016-08-02 10 views
-1

Ich versuche, Elemente aus einer Datenbank in eine Liste hinzuzufügen, anstatt sie statisch aus aspx hinzuzufügen. Ich habe diese Methode erstellt, und obwohl sie kompiliert wird, fügt sie keine Listenelemente zu meiner Dropdown-Liste hinzu. Hier ist ein Code, und ich bin bereit, mehr zur Verfügung zu stellen, wenn es sein muss. Die fragliche Methode ist addListItemsToPage().Warum fügt diese Methode keine Elemente zu einer Dropdownliste hinzu?

C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace EndophthalmitisDatabase { 
    public partial class DataEntry : System.Web.UI.Page { 
     protected void Page_Load(object sender, EventArgs e) { 
      addListItemsToPage(); 
     } 

     protected void addListItemsToPage() { 
      EndophthalmitisDBDataContext dbContext = new EndophthalmitisDBDataContext(); 

      for (int i=0; dbContext.Hospital_Datas.Count() < i; i++){ 
       int id = dbContext.Hospital_Datas.ElementAt(i).HospitalID; 
       string str = dbContext.Hospital_Datas.ElementAt(i).Hospital_Name; 

       ListItem li = new ListItem(); 
       li.Text = str; 
       li.Value = id.ToString(); 

       hospitalDDL.Items.Add(li); 
      } 

     } 

     protected void submitEndoDataBtn_Click(object sender, EventArgs e) 
     { 
      using (EndophthalmitisDBDataContext dbContext = new EndophthalmitisDBDataContext()) { 
       Occurrence_Data occData = new Occurrence_Data 
       { 
        LastName = lastNameTB.Text, 
        FirstName = firstNameTB.Text, 
        MRN = int.Parse(mrnTB.Text), 
        DateOfOccurence = DateOfOccurenceCal.SelectedDate, 
        InterventionProcedureDone = int.Parse(InterventionDDL.SelectedValue), 
        PreOccurrencePhysician = int.Parse(InterventionSurgeonDDL.SelectedValue), 
        LabsSent = labsSentCB.Checked, 
        PrecipitatingCausePreviousSurgery = int.Parse(preCauseDDL.SelectedValue), 
        PostOccurrencePhysician = int.Parse(preSurgeonDDL.SelectedValue), 
        DateOfPreviousSurgery = datePrecipitatingCal.SelectedDate, 
        Hospital = int.Parse(hospitalDDL.SelectedValue), 
        AdditionalInformation = moreInfoTB.Text 
       }; 

       lastNameTB.Text = ""; 
       firstNameTB.Text = ""; 
       mrnTB.Text = ""; 
       labsSentCB.Checked = false; 
       moreInfoTB.Text = ""; 

       dbContext.Occurrence_Datas.InsertOnSubmit(occData); 
       dbContext.SubmitChanges(); 
      } 
     } 
    } 
} 

aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MainSite.Master" AutoEventWireup="true" CodeBehind="DataEntry.aspx.cs" Inherits="EndophthalmitisDatabase.DataEntry" %> 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="mainContent" runat="server"> 
    <div class="formBox"> 
     <p style="text-align: center">Please use the area below to enter Data.</p> 
     <div class = "dataEntryForm"> 
      <form id = "occurrenceForm" runat = "server"> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Last Name</div> 
        <div class ="dataRowEntrance"> 
         <asp:TextBox ID = "lastNameTB" runat = "server"></asp:TextBox> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Last Name</div> 
        <div class ="dataRowEntrance"> 
         <asp:TextBox ID = "firstNameTB" runat = "server"></asp:TextBox> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">MRN</div> 
        <div class ="dataRowEntrance"> 
         <asp:TextBox ID = "mrnTB" runat = "server"></asp:TextBox> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Date of Occurence</div> 
        <div class ="dataRowEntrance"> 
         <asp:Calendar ID="DateOfOccurenceCal" runat="server"></asp:Calendar> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Intervention</div> 
        <div class ="dataRowEntrance"> 
         <asp:DropDownList ID="InterventionDDL" runat="server"> 
          <asp:ListItem Value ="1">Phaco</asp:ListItem> 
          <asp:ListItem Value ="2">Injection</asp:ListItem> 
          <asp:ListItem Value ="3">Retina Surgery</asp:ListItem> 
          <asp:ListItem Value ="4">Transplant</asp:ListItem> 
          <asp:ListItem Value ="5">Other</asp:ListItem> 
         </asp:DropDownList> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Intervention Surgeon</div> 
        <div class ="dataRowEntrance"> 
         <asp:DropDownList ID="InterventionSurgeonDDL" runat="server"> 
          <asp:ListItem Value ="8">Tabin</asp:ListItem> 
          <asp:ListItem Value ="9">Crandal</asp:ListItem> 
         </asp:DropDownList> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Labs sent</div> 
        <div class ="dataRowEntrance"> 
         <asp:CheckBox ID="labsSentCB" runat="server" /> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Precipitating Cause</div> 
        <div class ="dataRowEntrance"> 
         <asp:DropDownList ID="preCauseDDL" runat="server"> 
          <asp:ListItem Value ="1">Phaco</asp:ListItem> 
          <asp:ListItem Value ="2">Injection</asp:ListItem> 
          <asp:ListItem Value ="3">Retina Surgery</asp:ListItem> 
          <asp:ListItem Value ="4">Transplant</asp:ListItem> 
          <asp:ListItem Value ="5">Other</asp:ListItem> 
         </asp:DropDownList> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Precipitating Surgeon</div> 
        <div class ="dataRowEntrance"> 
         <asp:DropDownList ID="preSurgeonDDL" runat="server"> 
          <asp:ListItem Value ="8">Tabin</asp:ListItem> 
          <asp:ListItem Value ="9">Crandal</asp:ListItem> 
         </asp:DropDownList> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Data of Precipitating Cause</div> 
        <div class ="dataRowEntrance"> 
         <asp:Calendar ID ="datePrecipitatingCal" runat="server"></asp:Calendar> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Hospital</div> 
        <div class ="dataRowEntrance"> 
         <asp:DropDownList ID ="hospitalDDL" runat="server"> 
         </asp:DropDownList> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText">Additional Information</div> 
        <div class ="dataRowEntrance"> 
         <asp:TextBox ID ="moreInfoTB" runat="server" Rows ="100"></asp:TextBox> 
        </div> 
       </div> 
       <div class ="dataRow"> 
        <div class ="dataRowText"> 
         <asp:Button ID ="submitEndoDataBtn" runat="server" Text="Submit" OnClick ="submitEndoDataBtn_Click"/> 
        </div> 
       </div> 
      </form> 
     </div> 
    </div> 
</asp:Content> 
+0

Ist das Proof of Concept? Oder "echter" Code? Wenn letzteres, lesen Sie bitte http://www.hanselman.com/blog/AReminderOnThreeMultiTierLayerArchitectureDesignBroughtToYouByMyLateNightFrustrations.aspx – granadaCoder

+0

Die Art und Weise Ihren Code strukturiert ist, es wäre besser, um die Liste zu materialisieren vollständig aus dem db Kontext zunächst statt immer die DbSet verweist. – Igor

+0

Sein "echter Code" Ich bin mir nicht sicher, was du meinst ... – Darokrithia

Antwort

5

Ihre for Schleifenbedingung falsch ist, auf seine Notwendigkeit

for (int i=0; i < dbContext.Hospital_Datas.Count(); i++) 
+0

Danke, manchmal sind es die einfachsten Dinge, die ich übersehen habe. – Darokrithia

+1

kein Problem, es passiert :) – Mostafiz

1

OMG, das ist sehr schlecht p Gegenteil ractice. Sie werden die DB jedes Mal aufrufen, wenn Sie die Schleife betreten.

protected void addListItemsToPage() { 
    EndophthalmitisDBDataContext dbContext = new EndophthalmitisDBDataContext(); 

    hospitalDDL.DataTextField = "Hospital_Name"; 
    hospitalDDL.DataValueField = "HospitalID" 

    hospitalDDL.DataSource = dbContext.Hospital_Datas.ToList(); 
    hospitalDDL.DataBind(); 

    } 
3
  1. immer deine DbContext Schöpfung in einer using Anweisung wickeln oder es in Ihrer enthaltenden Klasse verfügen, wenn sein auf Klassenebene scoped. Ihr Bereich ist in der Methode begrenzt und Ihr Code abondon es ohne Entsorgung (schlechte Praxis!)
  2. Ihre for Anweisung war falsch, aber Sie brauchen wirklich keine for, könnten Sie eine foreach verwenden, die viel einfacher zu lesen wäre ODER Verwenden Sie Datenbindung wie von Ashkan vorgeschlagen.
  3. Sie könnten es auch zu einer einzigen Aussage zusammenfassen, sehen Sie das OR im Kommentar unten im Code. Dies verwendet eine Lambda Anweisung.

Code:

protected void addListItemsToPage() { 
    // wrap this in a using statement so the connection is closed and disposed 
    using(EndophthalmitisDBDataContext dbContext = new EndophthalmitisDBDataContext()) 
    { 
     // replaced your wrong for statement with a foreach because you do not need a for statement (you are not using the indexer in a way that added any benifit) 
     foreach(var hospital in dbContext.Hospital_Datas) 
      ListItem li = new ListItem(); 
      li.Text = hospital.Hospital_Name; 
      li.Value = hospital.HospitalID; 

      hospitalDDL.Items.Add(li); 
     } 


     // OR you could write it as a single statement 
     hospitalDDL.AddRange(dbContext.Hospital_Datas.Select(hospital => new ListItem(){Text = hospital.Hospital_Name, Value = hospital.HospitalID})); 
    } 
} 
+0

Vielen Dank für den Hinweis. Ich bin sehr neu zu Linq zu SQL; Warum sollte ich über dbcontext verfügen? Über welche anderen Gegenstände sollte ich verfügen? Ich werde versuchen hinzuzufügen, was Sie empfohlen haben. – Darokrithia

+1

@Darokrithia - Alles, was die Schnittstelle 'System.IDisposable' implementiert. Dies sind in der Regel Typen, die externe Ressourcen wie Datenbankverbindungen oder Dateiströme oder Netzwerkstreams usw. verwenden. Wenn Sie 'Dispose' nicht aufrufen, wenn Sie damit fertig sind, lassen Sie die Ressource möglicherweise offen, bis die Speicherbereinigung stattfindet (möglicherweise gefördert zu gen2). Eine using-Anweisung stellt sicher, dass, wenn der Umfang des Blocks verlassen wird, das Dispose aufgerufen wird (Sie können nur die Verwendung von Disposable-Typen verwenden). In Ihrem Fall würden Sie Datenbankverbindungen offen lassen. – Igor

Verwandte Themen