Have you ever misspelled a ViewState Variable Name? If you have, you probably found out only after trying to debug to find why your Web App was not running. Using ViewState properties gives Intellisense and removes the chance of misspelling the name of the ViewState variable name.
The code below shows a bad way to access a value from ViewState, yet if you are just starting ASP.NET development, it might seem the natural thing to do.
| int page = ViewState["Step"]; |
| private int VSStep { get { if (ViewState["VSStep"] == null) { ViewState["VSStep"] = 0; } return int.Parse(ViewState["VSStep"].ToString()); } set { ViewState["VSStep"] = value; } } private string VSPin { get { if (ViewState["VSPin"] == null) { ViewState["VSPin"] = string.Empty; } return ViewState["VSPin"].ToString(); } set { ViewState["VSPin"] = value; } } |
| int page = VSStep; string pin = VSPin; |
| Public Sub CreateViewStateProperty() Dim name As String = InputBox("Enter name for ViewState Property, Type", "ViewState Property Creation", "") If name.Trim() = String.Empty Then Exit Sub Dim nameType As String() = name.Split(",") If nameType.Length < 2 Then Exit Sub Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection) Dim sb As StringBuilder = New StringBuilder(1000) Dim vsName As String = String.Format("ViewState[""{0}""]", nameType(0)) Dim type As String = nameType(1) sb.Append(String.Format("private {0} {1}", nameType(1), nameType(0)) & vbCrLf) sb.Append("{" & vbCrLf) sb.Append(" get" & vbCrLf) sb.Append(" {" & vbCrLf) sb.Append(" if (" & vsName & " == null)" & vbCrLf) sb.Append(" {" & vbCrLf) If type = "string" Then sb.Append(" " & vsName & " = string.Empty;" & vbCrLf) ElseIf type = "int" OrElse type = "decimal" Then sb.Append(" " & vsName & " = 0;" & vbCrLf) ElseIf type = "DateTime" Then sb.Append(" " & vsName & " = DateTime.Now;" & vbCrLf) Else sb.Append(" " & vsName & " = null;" & vbCrLf) End If sb.Append(" }" & vbCrLf) sb.Append(vbCrLf) If type = "string" Then sb.Append(" return " & vsName & ".ToString();" & vbCrLf) ElseIf type = "int" Then sb.Append(" return int.Parse(" & vsName & ".ToString());" & vbCrLf) ElseIf type = "DateTime" Then sb.Append(" return Convert.ToDateTime(" & vsName & ");" & vbCrLf) Else sb.Append(" return " & vsName & ";" & vbCrLf) End If sb.Append(" }" & vbCrLf) sb.Append(" set" & vbCrLf) sb.Append(" {" & vbCrLf) sb.Append(" " & vsName & " = value;" & vbCrLf) sb.Append(" }" & vbCrLf) sb.Append("}" & vbCrLf) ts.Insert(sb.ToString()) End Sub |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |