0

我们希望我们的管理员从下拉列表中选择一个用户,并将与该用户关联的一个或多个角色显示在一个复选框中。

当我尝试运行下面的代码时,我得到

将 varchar 值“John Mayer”转换为数据类型 int 时转换失败

任何想法如何解决这个问题?

下面是我正在使用的代码。

'//Markup
<p>
     <b>Select a User:</b> 
     <asp:DropDownList ID="UserList" runat="server" AutoPostBack="True" 
          DataTextField="UserName" DataValueField="LoginId" OnSelectedIndexChanged="UserList_SelectedIndexChanged"> 

     </asp:DropDownList> 
</p> 
<p> 
    <div class="roleList">
        <asp:CheckBoxList ID="RoleList" runat="server">
        </asp:CheckBoxList>
    </div>

'//CodeBehind
Public Sub PopulateUserList()
        Dim cmd As New SqlCommand("Select LoginId,UserName from tblLogin", New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString))
        cmd.Connection.Open()

        Dim ddlValues As SqlDataReader
        ddlValues = cmd.ExecuteReader()

        UserList.DataSource = ddlValues
        UserList.DataValueField = "LoginId"
        UserList.DataTextField = "UserName"
        UserList.DataBind()

        cmd.Connection.Close()
        cmd.Connection.Dispose()
    End Sub

    Protected Sub UserList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)

        Dim conn As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString

        Dim ds As DataSet = New DataSet()

        Dim sql As String = "select UserRoles from tblLogin where userName = " + UserList.SelectedValue

        Dim AD As New SqlDataAdapter(sql, conn)
        AD.Fill(ds, "table")

        RoleList.DataSource = ds.Tables(0)
        RoleList.DataTextField = "UserRoles"
        RoleList.DataValueField = "LoginId"
        RoleList.DataBind()

    End Sub

谢谢

4

1 回答 1

2

可能您还需要从表中检索 LoginID 而不仅仅是 UserRoles

Protected Sub UserList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)

    Dim conn As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString

    Dim ds As DataSet = New DataSet()

    Dim sql As String = "select LoginId, UserRoles from tblLogin " + 
                        "where userName = @uname"

    Dim AD As New SqlDataAdapter(sql, conn)
    AD.SelectCommand.Parameters.AddWithValue("@uname",  UserList.SelectedItem.Text)
    AD.Fill(ds, "table")

    RoleList.DataSource = ds.Tables(0)
    RoleList.DataTextField = "UserRoles"
    RoleList.DataValueField = "LoginId"
    RoleList.DataBind()
于 2013-06-29T15:59:33.963 回答