2010-02-18 91 views
1

我在.aspx.vb中創建了一個htmltable,因爲我有很多來自數據庫的行,它們依賴於查詢字符串。那部分是好的。但是當有人在其中一個單元格中進行更改時,我如何將數據保存回數據庫?我點擊提交後,如何添加htmltablecell數據到數據庫

碼 -

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 

請詳細回答。

+0

有人嗎?這個問題很難嗎? – iuers 2010-02-18 01:34:54

+0

變量「rd」代表什麼?另外,你的頁面中的哪一部分是代碼發生的第一部分? Page_Load中? – 2010-02-18 02:19:26

+0

rd是sqldatareader。第一個片段確實發生在page_load – iuers 2010-02-18 19:23:39

回答

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() 

讓我知道您是否需要任何額外的輔助。如果不是,請將此標記爲正確答案。

+0

我必須使用html表格,代碼已經完成。現在如何將文本框中的新值保存到數據庫中? – iuers 2010-02-18 19:23:04

+0

iuers,我更新了我的代碼。這是否解決你的問題? – 2010-03-01 17:48:47