2015-01-21 4 views
0

У меня есть следующий код, который заполняет метку ASP.net со значениями, извлекаемых из SP и CachedTable:Как заполнить DropDownList на основе DataTable

public void UpdateDropDownList() 
{ 
    string strQuery = ""; 

    using (SqlConnection scCon = new SqlConnection(connString)) 
    { 
     using (SqlCommand scCmd = new SqlCommand("cation", scCon)) 
     { 
      SqlDataAdapter sda = new SqlDataAdapter(); 
      DataTable dt = new DataTable(); 
      scCmd.CommandType = CommandType.StoredProcedure; 

      scCmd.Parameters.Add("@ation", SqlDbType.VarChar).Value = cation.SelectedItem.Value; 

      sda.SelectCommand = scCmd; 
      sda.Fill(dt); 

      var distinctValues = dt.AsEnumerable() 
        .Select(row => row.Field<string>("Specialty")) 
        .Distinct(); 
      Label1.Text = "All Specialties<br/>"; 
      Label1.Text += string.Join("<br />", distinctValues); //Displays all specialties related to the location 
      var k = distinctValues.ToArray(); 
      strQuery = "("; 
      for (int y = 0; y < k.Length; y++) 
      { 
       if (y == 0) 
       { 
        strQuery += @"[Specialty] = '" + k[y] + "'"; 
       } 
       else 
       { 
        strQuery += @" OR [Specialty] = '" + k[y] + "'"; 
       } 
      } 
      strQuery += @") AND ([Location] = '" + Location.SelectedItem.Value + "')"; 
      DataTable cacheTable2 = HttpContext.Current.Cache["cachedtable"] as DataTable; //first cached table 
      DataTable filteredData2 = cacheTable2.Select(strQuery).CopyToDataTable<DataRow>(); 

      var distinctValues2 = filteredData2.AsEnumerable() 
        .Select(row => row.Field<string>("Name")) 
        .Distinct(); 
      Label1.Text += "All Providers<br/>"; 
      Label1.Text += string.Join("<br />", distinctValues2); //Displays all providers related to the location 

      strQuery = "([Specialty] = 'All Specialties'"; 
      for (int y = 0; y < k.Length; y++) 
      { 
       strQuery += @" OR [Specialty] = '" + k[y] + "'"; 
      } 
      strQuery += ")"; 
      DataTable cacheTable3 = HttpContext.Current.Cache["cachedtable2"] as DataTable; //different cached table 
      DataTable filteredData3 = cacheTable3.Select(strQuery).CopyToDataTable<DataRow>(); 

      var distinctValues3 = filteredData3.AsEnumerable() 
        .Select(row => row.Field<string>("Topic")) 
        .Distinct(); 
      Label1.Text += "All Topics<br/>"; 
      Label1.Text += string.Join("<br />", distinctValues3); //Displays all topics related to the specialty of that location 

      Session.Add("DTTableLocation", dt); 
     } 
    } 
} 

У меня есть четыре DROPDOWNLIST:

<asp:DropDownList ID="Location" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Location_SelectedIndexChanged"></asp:DropDownList> 
<asp:DropDownList ID="Specialty" runat="server" AutoPostBack="true"></asp:DropDownList> 
<asp:DropDownList ID="Name" runat="server" AutoPostBack="true"></asp:DropDownList> 
<asp:DropDownList ID="Topic" runat="server" AutoPostBack="true"></asp:DropDownList> 

Вышеупомянутый код C# выполнен для Location_SelectedIndexChanged.

Как я могу заменить следующее:

Label1.Text = "All Specialties<br/>"; 
Label1.Text += string.Join("<br />", distinctValues); //Displays all specialties related to the location 

с наполнением Specialty DropDownList (The DataField и DataValue этого значение).

Label1.Text += "All Providers<br/>"; 
Label1.Text += string.Join("<br />", distinctValues2); //Displays all providers related to the location 

с наполнении Name DropDownList (The DataField и DataValue это значение).

Label1.Text += "All Topics<br/>"; 
Label1.Text += string.Join("<br />", distinctValues3); //Displays all topics related to the specialty of that location 

с наполнении Topic DropDownList (The DataField и DataValue это значение).

ответ

0
Specialty.DataSource = distinctValues 
Specialty.DataBind() 

Вам может понадобиться настроить DataTextField и DataValueField свойства, но я не могу сказать, что те должны быть.

Сделайте то же самое для всех трех dropdownlists.

Я бы также разделил этот код на отдельные функции. Может быть GetSpecialties, который извлекает все специальности из базы данных. GetProviders, который строит запрос и возвращает поставщиков из кэшированной таблицы. И GetTopics, который строит этот запрос и возвращает темы.

Это сделает основную функцию намного короче и понятнее. Как сейчас, это очень трудно читать.

var distinctSpecialties = GetSpecialties(); 
Specialty.DataSource = distinctSpecialties; 
Specialty.DataBind(); 

var distinctProviders = GetProviders(distinctSpecialties); 
Name.DataSource = distinctProviders; 
Name.DataBind(); 

var distinctTopics = GetTopics(distinctSpecialties); 
Topic.DataSource = distinctTopics; 
Topic.DataBind(); 
+0

Я попробовал верхний код и DropDownList пустой ... – SearchForKnowledge

+0

'DataBinding:«System.String»не содержит свойство с именем«Specialty'.' – SearchForKnowledge

+0

я не уверен, где вы находитесь ссылаясь на свойство с именем Specialty, кроме того, когда вы извлекаете его из базы данных. – nickles80

Смежные вопросы