【问题标题】:Pre-select the values in a multi-select listbox based on records in query results根据查询结果中的记录预选多选列表框中的值
【发布时间】:2016-01-30 19:46:54
【问题描述】:

想象一下这张桌子:

MatchID UserID  MatchField        MatchValue
7          5    MatchInterests        3
8          5    MatchInterests        7
9          5    MatchInterests       12
10         5    MatchInterests       20
11         5    MatchInterests       26
12         2    MatchInterests        7
13         2    MatchInterests       26
14         4    MatchInterests       26
15         5    MatchStates          12
16         5    MatchStates          11
17         2    MatchStates           1
18         2    MatchStates          17
19         4    MatchStates          10

我想要做的是在用户 5 的列表框中为字段 MatchInterests 预先选择 MatchValues 值。所以我想要预选的结果数据集如下所示:

MatchID UserID  MatchField        MatchValue
7          5    MatchInterests        3
8          5    MatchInterests        7
9          5    MatchInterests       12
10         5    MatchInterests       20
11         5    MatchInterests       26

最好的方法是什么?

我试图做的是:

string strSQL2 = "SELECT MatchValue FROM tmpUsermatch WHERE MatchField = 'MatchInterests' AND UserID = '" + (DT2["UserID"].ToString()) + "'";
Interests.SelectionMode = ListSelectionMode.Multiple;
using (var con = new SqlConnection(strCon1))
using (var adapter2 = new SqlDataAdapter(strSQL2, con))
   {
     DataTable dt2 = new DataTable();
     adapter2.Fill(dt2);
     foreach (DataRow row in dt2.Rows)
     {
       Interests.SelectedValue = row["MatchValue"].ToString();
     }
   }

这可行,但只会导致选择数据集的 last 记录中的值,我需要选择 每个 记录中的值。

应要求:控件名称兴趣标记。

<tr>
   <td style="width:160px">
      <asp:Label ID="Label26" runat="server" AssociatedControlID="Interests">Interests:</asp:Label>
   </td>
   <td style="width:300px">
      <div id="UCStyle1">
        <asp:ListBox ID="Interests" SelectionMode="Multiple" runat="server">
        </asp:ListBox>
      </div>
   </td>
</tr>

【问题讨论】:

  • 共享名为Interests的控件的标记

标签: c# asp.net visual-studio-2010 code-behind jquery-multiselect


【解决方案1】:

您在循环的每次迭代中都有效地覆盖了SelectedValue,这就是为什么您只看到最后一个被选中的原因。

您需要在项目本身上设置Selected 属性或使用ListBox.SetSelected() 方法。方法的documentation page上有一个例子。

所以,而不是

Interests.SelectedValue = row["MatchValue"].ToString();

你会的

Interests.SetSelected(x, true);

其中x 是您要选择的列表项的索引。您可能需要通过例如计算索引如果您手头没有可用的索引,请根据 row["MatchValue"] 获取项目。

【讨论】:

  • 您能详细说明一下吗?那个页面对我一点帮助都没有。
猜你喜欢
  • 2019-12-07
  • 2012-03-03
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 2017-11-15
相关资源
最近更新 更多