在Repeater中的DropDownList中设置SelectedValue

时间:2013-12-26 17:48:26

标签: asp.net vb.net

我如何使这项工作完全太难看,所以我知道我必须遗漏一些东西...... 告诉我如何以更好的方式设置DDL的SelectedValue。 我已经尝试在DropDownList标记中设置SelectedValue并在OnDataBound事件中使用Eval(“b.codeID”),它给我一个“数据绑定方法,如Eval(),XPath()和Bind()只能使用在数据绑定控制的背景下。“错误。 下面的代码现在可以正常工作。我不喜欢它是必须将一个asp:Label绑定到b.CatID只是为了在OnDataBound事件中引用它以在For Each循环中使用它。我应该能够以更优雅的方式获得eval(“b.CodeID”)的值。

<asp:Repeater ID="rptLabor" runat="server" OnItemCommand="button_click" OnItemDataBound="rptLaborDataBound">
 <td><asp:DropDownList ID="ddlLaborCodeEdit" runat="server"></asp:DropDownList>
 <asp:Label ID="lblddlLaborCodeEdit" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "b.catid")%>' Visible="false"></asp:Label></td>

Sub rptLaborDataBound(ByVal s As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
    If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
        Dim ddlLaborCode As DropDownList = CType(e.Item.FindControl("ddlLaborCodeEdit"), DropDownList)
        Dim lblLaborCode As Label = CType(e.Item.FindControl("lblddlLaborCodeEdit"), Label)

            SetddlLaborBillCode(ddlLaborCode)


        For Each item As System.Web.UI.WebControls.ListItem In ddlLaborCode.Items
            If item.Value = lblLaborCode.Text Then
                item.Selected = True
                Exit For
            End If
        Next

Protected Sub SetddlLaborBillCode(ByVal ddl As DropDownList)
    Dim db As New TtCSIDataContext
    Dim sel = (From a In db.tblBillCodesByClients _
              Where a.ClientID = ddlClient.Text And a.Grp = "LAB" _
              Select a.CodeID, Code = a.Code & " | " & a.CodeDescr).ToList

    ddl.DataSource = sel
    ddl.DataTextField = "Code"
    ddl.DataValueField = "CodeID"
    ddl.DataBind()
End Sub

1 个答案:

答案 0 :(得分:0)

我现在看到你对标记绑定问题的看法。好吧,希望我至少可以帮助你清理当前的方法。

我删除了Label,只是从ItemDataBound事件中的e.Item.DataItem属性中获取“b.catid”的值。

此外,由于您确信“b.catid”的值将位于DropDownList的值列表中,因此您可以直接设置SelectedValue(而不是循环遍历项目)。

标记:

<asp:Repeater ID="rptLabor" runat="server" OnItemCommand="button_click" 
    OnItemDataBound="rptLaborDataBound">
    <td>
        <asp:DropDownList ID="ddlLaborCodeEdit" runat="server">
        </asp:DropDownList>
    </td>

VB.NET代码:

Sub rptLaborDataBound(ByVal s As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)

    If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
        Dim ddlLaborCode As DropDownList = CType(e.Item.FindControl("ddlLaborCodeEdit"), DropDownList)
        Dim catIDCode As String = CType(e.Item.DataItem("b.catid"), String)

        SetddlLaborBillCode(ddlLaborCode)       
        ddlLaborCode.SelectedValue = catIDCode

    ...