我想更改文本框信息但是当我尝试这样做时,它不会工作 这是我的asp.net vb代码
Imports System.Data.SqlClient
导入System.Data Imports 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)
您应该始终考虑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使用的模式,可能会破坏您的数据库或从您的表中窃取有价值的信息