Падащ списък не показва правилната избрана стойност в ASP.NET Repeater Web приложение

+5 гласа
47 прегледа
попитан 2016 май 13 в .NET от Nikoleta.V. (4,090 точки)
редактиран 2016 май 13 от Nikoleta.V.
Имам няколко ASP.NET Repeater-а, които имат падащи менюта в тях и трябва само да се напълнят с правилната информация и след това да покажат избраната стойност за всеки ред, който се показва. В единия repeater(CompanyRepeater), правилната стойност е избрана. В друг(SoldRepeater) правилната стойност не е избрана. Иначе казано, в единия работи,а в другия не. Кодът е същия и за двата и не мога да разбра защо вторият не работи. И двата падащи списъка се пълнят с правилната информация, но втория repeater не показва правилно избраната стойност. Помогнете ми да разбера защо става така. Долу съм сложил кода. Всяка помощ ще е добре дошла.

Кода съм го сложила в отделни коментари в следващ коментар

1 отговор

0 гласа
отговорени 2016 май 13 от Nikoleta.V. (4,090 точки)
Ето го и фронт-енд кода:  

<asp:Repeater ID="CompanyRepeater" runat="server" OnItemDataBound="CompanyRepeater_ItemDataBound" OnItemCommand="CompanyRepeater_ItemCommand">

   <ItemTemplate>

      <table>

         <tr>

            <td colspan="3" style="text-align: center;">

               <h3 style="font-weight: bold;">Company</h3>

            </td>

         </tr>

         <tr>

            <td>Event Date:

               <br />

               <asp:TextBox ID="txtDate" runat="server" Text='<%#Eval("Date") %>'></asp:TextBox>

               <asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>

            </td>

            <td rowspan="2">Notes:

               <br />

               <asp:TextBox ID="txtNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>

            </td>

            <td>OldName

               <br />

               <asp:TextBox ID="txtOldNameChange" Text='<%#Eval("OldName") %>' runat="server"></asp:TextBox>

            </td>

         </tr>

         <tr>

            <td>Country:

               <asp:DropDownList ID="ddlCountry" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>

               <br /> State:

               <asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>

            </td>

            <td>New Name

               <br />

               <asp:TextBox ID="txtNewNameChange" runat="server" Text='<%#Eval("NewName") %>'></asp:TextBox>

            </td>

            <td rowspan="3" style="width: 50px; float: right;">

               <asp:Button ID="btnUpdateName" runat="server" Text="Update" CommandName="Update" />

               <br />

               <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />

            </td>

         </tr>

      </table>

   </ItemTemplate>

   <SeparatorTemplate>

      <p>&nbsp;</p>

      <br />

   </SeparatorTemplate>

</asp:Repeater>

<hr />

<asp:Repeater ID="SoldRepeater" runat="server" OnItemDataBound="SoldRepeater_ItemDataBound" OnItemCommand="SoldRepeater_ItemCommand">

   <ItemTemplate>

      <table>

         <tr>

            <td colspan="3" style="text-align: center;">

               <h3 style="font-weight: bold;">Sold Event</h3>

            </td>

         </tr>

         <tr>

            <td>Event Date:

               <br />

               <asp:TextBox ID="txtSoldDate" runat="server" Text='<%#Eval("EventDate") %>'></asp:TextBox>

               <asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>

            </td>

            <td rowspan="2">Notes:

               <br />

               <asp:TextBox ID="txtSoldNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>

            </td>

            <td>Sold to Company

               <br />

               <asp:TextBox ID="txtSoldTo" Text='<%#Eval("SoldToCompany") %>' runat="server"></asp:TextBox>

               <br /> Sold to Type

               <asp:DropDownList ID="ddlSoldTo" runat="server"></asp:DropDownList>

            </td>

            <td rowspan="2">

               <asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%#Eval("CompID") %>' />

               <br />

               <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />

            </td>

         </tr>

      </table>

   </ItemTemplate>

   <SeparatorTemplate>

      <p>&nbsp;</p>

      <br />

   </SeparatorTemplate>

</asp:Repeater>
коментиран 2016 май 13 от Nikoleta.V. (4,090 точки)
Бек-енд кода:
protected void Page_Load(object sender, EventArgs e)
{
   _cID = Convert.ToInt32(Request.QueryString["CompID"]);
   if (!Page.IsPostBack)
   {
      PopulateCompanyRepeater();
      PopulateSoldEvent();
   }
}
private void PopulateCompanyRepeater()
{
   DALAccessData a = new DALAccessData(connString);
   _listInfo = a.GetCompInfo(_cID);
   CompanyRepeater.DataSource = _listInfo;
   CompanyRepeater.DataBind();
}
private void PopulateSoldEvent()
{
   DALSectionAccessData a = new DALSectionAccessData(connString);
   _listEvents = a.GetSoldEvents(_cID);
   SoldRepeater.DataSource = _listEvents;
   SoldRepeater.DataBind();
}
protected void CompanyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   {
      DropDownList ddl = (DropDownList)e.Item.FindControl("ddlCountry");
      DropDownList ddl2 = (DropDownList)e.Item.FindControl("ddlState");
      Corp co = (Corp)e.Item.DataItem;
      Corp st = (Corp)e.Item.DataItem;
 
      SqlDataAdapter sda;
      DataSet ds = new DataSet();
      try
      {
         using(cn = new SqlConnection(connString))
         {
            string s = "SELECT DISTINCT a.Country_ID, a.CountryName FROM States c INNER JOIN Countries a ON a.Country_ID = c.Country_ID";
            cn.Open();
            sda = new SqlDataAdapter(s, cn);
            sda.Fill(ds);
            ddl.DataSource = ds.Tables[0];
            ddl.DataTextField = "CountryName";
            ddl.DataValueField = "Country_ID";
            ddl.DataBind();
            cn.Close();
         }
      }
      catch (Exception ex)
      {
         throw new Exception(ex.Message);
      }
      for (int i = 0; i < ddl.Items.Count; i++)
      {
         if (co.Country_ID == Convert.ToInt32(ddl.Items[i].Value))
         {
            ddl.Items[i].Selected = true;
         }
         else
         {
            ddl.Items[i].Selected = false;
         }
      }
 
      try
      {
         using(cn = new SqlConnection(connString))
         {
            string s = "SELECT DISTINCT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
            cn.Open();
            sda = new SqlDataAdapter(s, cn);
            sda.Fill(ds);
            ddl2.DataSource = ds.Tables[0];
            ddl2.DataTextField = "StateName";
            ddl2.DataValueField = "StateID";
            ddl2.DataBind();
         }
      }
      catch (Exception ex)
      {
         throw new Exception(ex.Message);
      }
 
      for (int i = 0; i < ddl2.Items.Count; i++)
      {
         if (!String.IsNullOrEmpty(ddl2.Items[i].Value))
         {
            if (st.StateID == Convert.ToInt32(ddl2.Items[i].Value))
            {
               ddl2.Items[i].Selected = true;
            }
            else
            {
               ddl2.Items[i].Selected = false;
            }
         }
      }
   }
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList ddl = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlCountry");
   DropDownList ddl2 = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlState");
   ddl2.Items.Clear();
   using(SqlConnection conn = new SqlConnection(connString))
   {
      using(SqlCommand cmd = new SqlCommand())
      {
         cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
         cmd.Connection = conn;
         conn.Open();
         using(SqlDataReader sdr = cmd.ExecuteReader())
         {
            while (sdr.Read())
            {
               ListItem _listStates = new ListItem();
               _listStates.Text = sdr["StateName"].ToString();
               _listStates.Value = sdr["StateID"].ToString();
               ddl2.Items.Add(_listStates);
            }
         }
      }
   }
   ddl2.AppendDataBoundItems = true;
   ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
   ddl2.SelectedIndex = -1;
}
protected void SoldRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   {
      DropDownList ddl = (DropDownList)e.Item.FindControl("ddlSoldTo");
      int x = ((CorpEvents)e.Item.DataItem).SoldToTypeID;
      //Corp x = (Corp)e.Item.DataItem;
 
      SqlDataAdapter sda;
      DataSet ds = new DataSet();
      try
      {
         using(cn = new SqlConnection(connString))
         {
            string s = "SELECT SoldToTypeID, SoldToTypeName FROM SoldToType";
            cn.Open();
            sda = new SqlDataAdapter(s, cn);
            sda.Fill(ds);
            ddl.DataSource = ds.Tables[0];
            ddl.DataTextField = "SoldToTypeName";
            ddl.DataValueField = "SoldToTypeID";
            ddl.DataBind();
         }
      }
      catch (Exception ex)
      {
         throw new Exception(ex.Message);
      }
 
      for (int i = 0; i < ddl.Items.Count; i++)
      {
         if (x == Convert.ToInt32(ddl.Items[i].Value))
         {
            ddl.Items[i].Selected = true;
            //i = 9;
         }
         else
         {
            ddl.Items[i].Selected = false;
         }
      }
   }
}
коментиран 2016 май 13 от Nikoleta.V. (4,090 точки)
И data access слоя:
public List <Corp> GetCompInfo(int a)
{
   List <Corp> _listInfo = new List <Corp> ();
   DataTable dt = new DataTable();
   DataSet ds = new DataSet();
 
   //create the connection and command objects
   SqlConnection connection = new SqlConnection(_dbConnection);
   SqlCommand command = new SqlCommand();
   //populate the command object
   command.Connection = connection;
   command.CommandText = "SELECT a.CompID, CONVERT(varchar(10), a.Date, 120) AS Date, a.Notes, b.StateID, b.OldName, b.NewName, c.Country_ID FROM NameChange b INNER JOIN CompanyInfo a ON a.CompID = b.CompID INNER JOIN States c ON c.StateID = b.StateID WHERE a.CompID = " + a;
 
   using(connection)
   {
      using(command)
      {
         connection.Open();
         ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
            "MyTable"
         });
         dt = ds.Tables["MyTable"];
      }
   }
   foreach(DataRow row in dt.Rows)
   {
      Corp e = new Corp();
      e.CompID = Convert.ToInt32(row["CompID"].ToString());
      e.NewName = row["NewName"].ToString();
      e.OldName = row["OldName"].ToString();
      e.StateID = Convert.ToInt32(row["StateID"].ToString());
      e.Notes = row["Notes"].ToString();
      e.CountryID = Convert.ToInt32(row["Country_ID"].ToString());
      e.Date = Convert.ToDateTime(row["Date"].ToString());
      e.Date.ToShortDateString();
      _listInfo.Add(e);
   }
   return _listInfo;
}
public List <Corp> GetSoldEvents(int a)
{
   List <Corp> _listInfo = new List <Corp> ();
   DataTable dt = new DataTable();
   DataSet ds = new DataSet();
 
   //create the connection and command objects
   SqlConnection connection = new SqlConnection(_dbConnection);
   SqlCommand command = new SqlCommand();
   //populate the command object
   command.Connection = connection;
   command.CommandText = "SELECT a.CompID, a.Notes, a.Date, b.SoldToCompany, c.SoldToTypeName, c.SoldToTypeID FROM CompanyInfo a INNER JOIN SoldEvent b ON a.CompID = b.CompID INNER JOIN SoldToType c ON b.SoldToTypeID = c.SoldToTypeID WHERE a.CompID = " + a;
 
   using(connection)
   {
      using(command)
      {
         connection.Open();
         ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
            "MyTable"
         });
         dt = ds.Tables["MyTable"];
      }
   }
 
   foreach(DataRow row in dt.Rows)
   {
      Corp e = new Corp();
      e.CompID = Convert.ToInt32(row["CompID"].ToString());
      e.SoldToCompany = row["SoldToCompany"].ToString();
      e.SoldToTypeName = row["SoldToTypeName"].ToString();
      e.SoldToTypeID = Convert.ToInt32(row["SoldToTypeID"].ToString());
      e.Notes = row["Notes"].ToString();
      e.EventDate = Convert.ToDateTime(row["Date"].ToString());
      e.EventDate.ToShortDateString();
      _listInfo.Add(e);
   }
   return _listInfo;
}
...