Hi KatieNgoc,
Refer below sample.
HTML
CS.aspx
Name :
<asp:TextBox runat="server" ID="txtName" />
<asp:Button ID="Button1" Text="Login" runat="server" OnClick="Login" />
Default.aspx
<asp:Label ID="lblName" runat="server" />
<asp:TextBox runat="server" ID="txtData" />
<asp:Button Text="Print" runat="server" ID="btnPrint" /><br />
<asp:LinkButton ID="LinkButton1" Text="Logout" runat="server" PostBackUrl="~/CS.aspx" />
Namespaces
using System.Configuration;
using System.Data.SqlClient;
Code
CS.aspx.cs
protected void Login(object sender, EventArgs e)
{
Session["Name"] = txtName.Text;
Response.Redirect("Default.aspx");
}
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
int count = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = null;
con.Open();
count = GetCount(count, con, cmd);
if (count == 0)
{
cmd = new SqlCommand("INSERT INTO tblDatas VALUES(@Count,@Name)", con);
cmd.Parameters.AddWithValue("@Count", count + 1);
cmd.Parameters.AddWithValue("@Name", Session["Name"].ToString());
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("UPDATE tblDatas SET Count = @Count WHERE Name = @Name", con);
cmd.Parameters.AddWithValue("@Count", count + 1);
cmd.Parameters.AddWithValue("@Name", Session["Name"].ToString());
cmd.ExecuteNonQuery();
count = GetCount(count, con, cmd);
if (count >= 2)
{
txtData.Visible = false;
btnPrint.Visible = false;
}
}
con.Close();
lblName.Text = Session["Name"].ToString();
}
}
private int GetCount(int count, SqlConnection con, SqlCommand cmd)
{
cmd = new SqlCommand("SELECT Count from tblDatas WHERE Name = @Name", con);
cmd.Parameters.AddWithValue("@Name", Session["Name"].ToString().Trim());
count = Convert.ToInt16(cmd.ExecuteScalar());
return count;
}
Screenshot