无论我选择什么,我的Web表单都只插入下拉列表中的第一个项目

时间:2011-10-12 23:43:50

标签: asp.net visual-studio ms-access

我有两个关系表:Profiles表包含3种用户角色(Manager,Developer,Common User)和Users表,其中包含Access 2010数据库中用户及其角色ID(Profile_ID字段)的相关信息

我在ASP.NET中创建了一个Webform,它应该只是注册用户,询问他们的名字,在下拉列表中选择他们的角色并将其全部插入Access数据库。代码会为每个注册用户填充网格视图,并在页面加载时为每个角色填充下拉列表

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'Start connection
    Dim cs As String = ConfigurationManager.ConnectionStrings("Access 2010").ConnectionString
    Dim cn As New OleDbConnection(cs)
    cn.Open()

    'Retrieve User Data
    Dim cmd As New OleDbCommand
    With cmd
        .Connection = cn
        .CommandText = "SELECT * FROM Users"
        .CommandType = CommandType.Text
    End With
    Dim ddlValues As OleDbDataReader = cmd.ExecuteReader()

    'Populate User Grid View
    grdUsers.DataSource = ddlValues
    grdUsers.DataBind()
    ddlValues.Close()

    'Retrieve Profile data
    With cmd
        .Connection = cn
        .CommandText = "SELECT * FROM Profiles"
        .CommandType = CommandType.Text
    End With
    ddlValues = cmd.ExecuteReader()


    'Populate Dropdown Profiles
    ddRoles.DataSource = ddlValues
    ddRoles.DataTextField = "Nome"
    ddRoles.DataValueField = "ID"
    ddRoles.DataBind()

    'Close connections
    ddlValues.Close()
    cmd.Dispose()
    cn.Dispose()
End Sub

最近,只要点击一下按钮就会插入数据库:

Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
    Dim cs As String = ConfigurationManager.ConnectionStrings("Access 2010").ConnectionString
    Dim cn As New OleDbConnection(cs)
    Dim cmd As New OleDbCommand
    With cmd
        .CommandText = "INSERT INTO Users (nome, Profile_ID) VALUES ('" & Me.txtNome.Text & "', " & Me.ddRoles.SelectedValue & ")"
        .Connection = cn
        .Connection.Open()
        .ExecuteNonQuery()
        .Connection.Close()
        .Dispose()
    End With
    cn.Dispose()
    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

代码运行没有问题,但无论我选择的下拉列表中的哪个项目,它始终会创建为Common User(这是此表中的第一个记录)。虽然我检查了生成的html:

<select name="ctl00$MainContent$ddRoles" id="MainContent_ddRoles">
<option value="5">Common User</option>
<option value="6">Developer</option>
<option value="7">Manager</option>

似乎没错,但我的数据库只有ID号为5的记录。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

你通过绑定每次调用Page_Load来剔除DropDown列表中的选择。你只需要绑定!IsPostback。