asp.net从下拉列表中更新数据库

时间:2013-04-08 09:59:33

标签: asp.net vb.net drop-down-menu sql-update

我正在尝试允许用户选择将更新数据库中字段的婚姻状态。这是用户第一次使用时很好,但是如果他们想再次更新它,它就不会更新。

如果我选择数据源,如果他们希望更新,则在DDL中没有给出任何其他选项,而不是第一次选择的数据。

* ASPX *

<asp:DropDownList ID="DDLMarital" runat="server" TabIndex="1">
                <asp:ListItem Value = "Single" Text = "Single">Single</asp:ListItem>
                <asp:ListItem Value = "Married" Text = "Married">Married</asp:ListItem>
                <asp:ListItem Value = "Separated" Text = "Separated">Separated</asp:ListItem>
                <asp:ListItem Value = "Divorced" Text = "Divorced">Divorced</asp:ListItem>
            </asp:DropDownList>

** * * ASPX.VB * ****

'binding...

受保护的子Page_Load(发件人为对象,e为System.EventArgs)处理Me.Load

    Dim dvSql4 As DataView =
DirectCast(SqlMarital.Select(DataSourceSelectArguments.Empty), DataView)
    For Each drvSql4 As DataRowView In dvSql4
        DDLMarital.Text = drvSql4("Marital_Status").ToString()
    Next

End Sub

'单击“下一步”按钮时更新数据库 Protected Sub BtnNext_Click(sender As Object,e As System.EventArgs)处理BtnNext.Click

    Dim con As New SqlConnection
    Dim cmd As New SqlCommand

    con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\scrummingit2.mdf;Integrated Security=True;User Instance=True"
    con.Open()

    cmd.Connection = con
    cmd.CommandText = ("UPDATE Student_Personal_Details SET Marital_Status = @Marital WHERE Student_No = @StudentNo")

    Dim maritalParam As New SqlParameter("@Marital", DDLMarital.Text)
    Dim studentNoParam As New SqlParameter("@StudentNo", lblEnrolmentStudentNumber.Text)

    lblEnrolmentStudentNumber.Text = Session("Student")

    cmd.Parameters.Add(maritalParam)
    cmd.Parameters.Add(studentNoParam)

    cmd.ExecuteNonQuery()

    con.Close()

End Sub

有人可以帮忙吗?在Google没有找到任何答案的日子之后,现在变得绝望。

1 个答案:

答案 0 :(得分:1)

您应检查P​​ostBack,并仅在不是PostBack时指定所选值。

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
   If Not IsPostBack
        Dim dvSql4 As DataView =
    DirectCast(SqlMarital.Select(DataSourceSelectArguments.Empty), DataView)
        For Each drvSql4 As DataRowView In dvSql4
            DDLMarital.Text = drvSql4("Marital_Status").ToString()
        Next
   End If
End Sub

当每个Load

重置值时,用户的选择将被忽略