2014-05-04 67 views
-3

我想改變文本框的信息,但是當我嘗試這樣做,它不工作 這是我的asp.net VB代碼與DataReader的asp.net更新不工作

Imports System.Data.SqlClient 

進口系統。數據 進口System.Data.SqlClient.SqlDataReader 偏類_Default 繼承System.Web.UI.Page

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 

    Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\napster\Documents\ZE.mdf;Integrated Security=True;Connect Timeout=30" 



    Dim queryString As String = "Update TEST Set chaine1= '" & TextBox1.Text & "' " 
    Dim connection As New SqlConnection(connectionString) 

    Dim command As New SqlCommand(queryString, connection) 

    connection.Open() 
    command.ExecuteNonQuery() 
    connection.Close() 

End Sub 

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 
    Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\napster\Documents\ZE.mdf;Integrated Security=True;Connect Timeout=30" 
    Dim queryString As String = "SELECT * from TEST " 
    Dim connection As New SqlConnection(connectionString) 

    Dim command As New SqlCommand(queryString, connection) 

    connection.Open() 
    Dim dataReader As SqlDataReader = command.ExecuteReader() 

    While dataReader.Read() 
     TextBox1.Text = dataReader.GetSqlString(3) 
    End While 
    TextBox1. 
End Sub 

末級

+0

'這是不行的'。如何描述什麼不起作用以及您收到的任何錯誤消息。 –

+0

我會在這裏留下這個:http://xkcd.com/327/ – oscilatingcretin

回答

0

您應該始終考慮ASP.NET模型的工作原理。

在ASP.NET中,當您單擊執行服務器端代碼(事件)的按鈕時,在調用事件處理程序代碼之前,始終會調用Page.Load事件。

在你的Page.Load中,你再次執行從數據庫中加載TextBox的代碼,但是這段代碼破壞了你輸入的文本框的內容。文本框被設置爲由數據庫提取的原始值,因此,當按鈕事件處理程序中的代碼被執行時,它將相同的值寫入數據庫。

要解決這種情況下,你需要把它添加到Page_Load事件

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 
    if Not IsPostBack Then 
     Dim connectionString As String = "......" 
     Dim queryString As String = "SELECT * from TEST " 
     Dim connection As New SqlConnection(connectionString) 
     Dim command As New SqlCommand(queryString, connection) 

     connection.Open() 
     Dim dataReader As SqlDataReader = command.ExecuteReader() 

     While dataReader.Read() 
      TextBox1.Text = dataReader.GetSqlString(3) 
     End While 
    End If 
End Sub 

說,請留意了,你在按鈕單擊事件的代碼是非常危險的,因爲您連接無論是由用戶輸入到一個字符串,然後作爲一個sql命令傳遞給數據庫。這是Sql Injection attacks所使用的模式,可能會破壞您的數據庫或竊取您的有價值的信息表