单击“提交”后,如何将htmltablecell数据添加到数据库

时间:2010-02-18 01:14:54

标签: vb.net

我在.aspx.vb中创建了一个htmltable,因为我有很多来自数据库的行,它们依赖于查询字符串。那部分没事。但当有人在其中一个单元格中进行更改时,如何将数据保存回数据库?

代码 -

Dim tr As New HtmlTableRow
Dim td As New HtmlTableCell
td = New HtmlTableCell
Dim txtbox1 As New TextBox
txtbox1.ID = "price_" & rd("id")
txtbox1.Text = rd("price")
td.Controls.Add(txtbox1)
tr.Cells.Add(td)
tb1.Rows.Add(tr)

现在当有人更改文本框中的价格时,如何将其保存在数据库中? 这是提交按钮的代码 -

Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
    Dim sqlcnn As SqlConnection = Nothing, sqlstr As String = "", sqlcmd As SqlCommand
    sqlstr = "UPDATE ???"
    sqlcmd = New SqlCommand(sqlstr, sqlcnn)
    sqlcmd.ExecuteScalar()
End Sub

请详细回答。

1 个答案:

答案 0 :(得分:1)

我建议使用内置网格控件。这是一个演练Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control 。最好从Walkthrough: Basic Data Access in Web Pages开始。

如果您选择继续使用HTML,那么根据您提供的内容,这是一种方法。您可以添加更新按钮并在该事件中尝试此代码:

'Create an update Command with the apropriate paramaters'
Dim sql = ("UPDATE SO_Prices SET Price = @Price WHERE ID = @ID")
Dim Cmd As New SqlCommand(sql, connection)
Cmd.Parameters.Add("@Price", SqlDbType.SmallMoney)
Cmd.Parameters.Add("@ID", SqlDbType.Int)

connection.Open()

'Loop through the fields returned'
For Each Key As String In Request.Form.Keys

    'Make sure you only process fields you want'
    If Key.StartsWith("price") Then

        'Pull the ID out of the field name by splitting on the underscore'
        ' then choosing the second item in the array'
        Dim ID As String = Key.Split("_")(1)

        'Update the paramaters for the update query'
        Cmd.Parameters("@ID").Value = ID
        Cmd.Parameters("@Price").Value = Request.Form(Key)

        'Run the SQL to update the record'
        Cmd.ExecuteNonQuery()

    End If
Next

connection.Close()

如果您需要任何额外的帮助,请告诉我。如果没有,请将此标记为正确答案。