Ref:Persist Data / Object / Variable values across PostBack in ASP.Net
Values of the local variable can be lost during postback so you have to use ViewState.
Set the count value in ViewState.
ViewState("Count") = counter
Before increasing the counter value you need to check the ViewState value and again assign the value to ViewState.
If ViewState("Count") IsNot Nothing Then
counter = Convert.toInt32(ViewState("Count"))
End If
counter = counter + 1
ViewState("Count") = counter
Example:
Here i will increament the counter value on ButtonClick
HTML:
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCount" runat="server" />
<asp:Button Text="Increament counter" OnClick="IncreamentCounter" runat="server" />
</div>
</form>
C#:
protected void IncreamentCounter(object sender, EventArgs e)
{
int counter;
if (ViewState["Count"] != null)
{
counter = Convert.ToInt32(ViewState["Count"]);
}
else
{
counter = 0;
}
counter = counter + 1;
ViewState["Count"] = counter;
this.lblCount.Text = counter.ToString();
}
VB:
Protected Sub IncreamentCounter(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim counter As Integer
If ViewState("Count") IsNot Nothing Then
counter = Convert.ToInt32(ViewState("Count"))
Else
counter = 0
End If
counter = counter + 1
ViewState("Count") = counter
Me.lblCount.Text = counter.ToString()
End Sub
Thank You.