当我试图在用户提交后将我的页面加载值放入数据库时,我有一个奇怪的准确性。
当页面加载时我有这个:
Public theProductName As String = ""
Dim theProductCategory As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadProductName()
End If
End Sub
Private Sub LoadProductName()
objConn = New MySqlConnection(product.strConnString)
objConn.Open()
strSQL = "SELECT id, name, category " & _
"FROM product " & _
"WHERE id = 4;"
Try
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
While dtReader.Read()
theProductName = dtReader("name")
theProductCategory = dtReader("category")
btnSubmit.Text = "Add Item to " & theProductName
End While
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
MsgBox("LoadProductName: " & ex.Message)
End Try
End Sub
当我在页面启动时检查这些值时,它们具有正确的值,甚至提交按钮都有产品名称。
然而,一旦我按下按钮后保存它,它就有了同样的变量吗?
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim productName As String = theProductName.Replace(" ", "-")
Dim imageName As String = productName & "\" & Trim(txtModel.Text) & ".jpg'"
Dim theCat as String = theProductCategory
End Sub
productName 此处没有任何内容 theCat
我可以俯瞰什么?
答案 0 :(得分:1)
这是因为您只有在第一次加载时没有回发时才读取theProductName
,然后不会保存在任何地方。
您可以将变量theProductName
放入视图状态,以便在回发后使其变为相同。
来自msdn的示例和更多评论:http://msdn.microsoft.com/en-us/library/ms227551(v=vs.85).aspx
答案 1 :(得分:1)
您必须使用ViewState
保留数据。因为您发布了数据以便丢失旧状态
public string ProductName
{
get
{
if( Viewstate["ProductName"] == null)
{
return string.Empty;
}
return (string)Viewstate["ProductName"];
}
set
{
Viewstate["ProductName"] = value;
}
}
设置值
ProductName = "your value";