Retrieve (Get) comma separated Cookie value as Array in ASP.Net using C# and VB.Net

nauna
 
on Jul 21, 2022 04:58 AM
389 Views

hello,

On Button click i want to store TextBox comma separated value in cookie.

It could be multiple values max 10 and when read so it should load it as list.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
PrinceG
 
on Jul 23, 2022 07:53 AM

Hi nauna,

Refer below example. For separate the numbers use split function.

For Read Write cookie refer ASP.Net Cookies: Read, Write (Save) and Remove (Delete) Cookies in ASP.Net using C# and VB.Net.

HTML

<asp:TextBox ID="txtNumbers" runat="server"></asp:TextBox><br />
<asp:Button ID="btnWrite" runat="server" Text="Write" OnClick="OnWrite" />
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="OnRead" /><hr />
<asp:GridView runat="server" ID="gvDetails" />

Code

C#

protected void OnWrite(object sender, EventArgs e)
{
    HttpCookie cookie = new HttpCookie("Numbers");
    cookie.Value = txtNumbers.Text.Trim();
    cookie.Expires = DateTime.Now.AddDays(30);
    Response.Cookies.Add(cookie);
    txtNumbers.Text = string.Empty;
}

protected void OnRead(object sender, EventArgs e)
{
    HttpCookie cookie = Request.Cookies["Numbers"];
    List<string> numbers = cookie.Value.Split(',').ToList();
    gvDetails.DataSource = numbers;
    gvDetails.DataBind();
}

VB.Net

Protected Sub OnWrite(sender As Object, e As EventArgs)
    Dim cookie As HttpCookie = New HttpCookie("Numbers")
    cookie.Value = txtNumbers.Text.Trim()
    cookie.Expires = DateTime.Now.AddDays(30)
    Response.Cookies.Add(cookie)
    txtNumbers.Text = String.Empty
End Sub

Protected Sub OnRead(sender As Object, e As EventArgs)
    Dim cookie As HttpCookie = Request.Cookies("Numbers")
    Dim numbers As List(Of String) = cookie.Value.Split(",").ToList()
    gvDetails.DataSource = numbers
    gvDetails.DataBind()
End Sub

Screenshot