How to prevent to adding two lists in asp.net? - asp.net

How to Prevent adding two controls or to lists ? I've tried this code but it doesn't work... Pease help!
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ViewState["check"] = "First_Time";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["check"] == "First_Time")
{
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
ViewState["check"] = "Scond_Time";
}
else
{
Response.Write("Sorry, Can't create a list on second time");
}
}

The problem with your approach is that the button click event is triggered on postback, hence your postback check in Page_Load is pointless.
Since the CheckBoxList.Items are stored in Viewstate by default(it implements IStateManager), why don't you simply check if the items are already added?
protected void Button1_Click(object sender, EventArgs e)
{
if (CheckBoxList1.Items.Count < 6)
{
CheckBoxList1.Items.Clear();
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
}
else
{
// don't use Response.Write to output messages but controls
Response.Write("Sorry, Can't create a list on second time");
}
}

Related

Unable to perform Session State in ASP.NET

I was trying to perform Session State in ASP.NET, but it always start from 1 in different pages.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["count"] = 0;
}
int count = (int)Session["count"];
count++;
Label1.Text = count.ToString();
Session["count"] = count;
}
// In Global.asax
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
void Session_Start(object sender, EventArgs e)
{ // start of Session
Session["count"] = 0;
}
void Session_End(object sender, EventArgs e)
{
}
}
I expect the count continues but not starts from 1 after re-visit the webform. Thanks!
if you want to display the total active user on your site, use application object instead of session object and on session_start you increase count and on session_end, decrease count.
protected void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}
void Session_Start()
{ // start of Session
Application["count"] += 1;
}
void Session_End()
{
Application["count"] -= 1;
}

How do I add a variable for the textbox ID inside a function?

public partial class _Default : System.Web.UI.Page
{
double[] array = new double[5];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
array[i] = Convert.ToDouble(TextBox(i+1).Text);
}
}
}
This is my code, I have 5 textboxes, I'd like to refer to them with the int (i) inside the loop.
array[i] = Convert.ToDouble(TextBox(i+1).Text);
the text boxes are named 'TextBox1' , 'TextBox2', 'TextBox3, etc.
Is it possible in C#?
You could if you use Control.FindControl
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TextBox currenTextBox = (TextBox) FindControl("TextBox" + i);
if (!string.IsNullOrEmpty(currenTextBox?.Text))
{
if (double.TryParse(currenTextBox.Text, out var result))
{
array[i] = result;
}
}
}
}

Incrementing variables in ASP.net on every button click

I want to increment date in every click ASP.NET.
But Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0.
I need to persist a value across postbacks but I don't how to do that. I would appreciate for any help.
Here is what I'am trying to do:
int myNumber = 0;
protected void Button1_Click1(object sender, EventArgs e)
{
lblDate.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(myNumber).ToShortDateString();
myNumber++;
}
Update:
My finaly goal is to get next weeks first day with next button and Previous week, I mean I want to forword and backword...
public int NextCount
{
get { return ViewState["Count"] != null ? (int)ViewState["Count"] : 7; }
set { ViewState["Count"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount+7;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount - 7;
}
But When I click Prev button .. there is delay with one click after two or three Click then reaction coming the same with next button when you click from prev to next. Maybe I have to store it in session?
I have updated your code below by using ViewState to handle this. Other easiest option would be storing the same in Session, Cache or Cookie.
While storing a value in ViewState, it will create a hidden field
in the page and store the value to maintain it across the postback.
public int NextCount
{
get { return ViewState["NextCount"] != null ? (int)ViewState["NextCount"] : 0; }
set { ViewState["NextCount"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
NextCount = NextCount+7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
NextCount = NextCount - 7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}

Have to press Enter Twice for a function to work C#

I have the following .aspx page. I'm searching for the words that are in the database, everything works fine. I also have a HyperLink which shows a message if the word does not exist in the database.
BUT the only problem is when I search for the word and the word is not in the database it doesn't show the HyperLink from the first time, I have to CLICK ENTER twice for it to work, and CLICK CLEAR twice for it to dissapear.
I know that the problem is that I have the button after the page_load, but I can't find the solution for it. What I've tried is created another function private void load_data() and copy everything from page_load into it. And in the load_page and button2_click just call load_data(); It doesn't work.
Here's the code:
namespace TRI_Portal.ScreenPop.Gloss
{
public partial class Gloss_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (GridView2.Rows.Count == 0)
{
HyperLink1.Visible = true;
}
else
{
HyperLink1.Visible = false;
}
String s = Request.QueryString["language"];
Language1.Text = Server.HtmlEncode(s);
}
}
}
I have tried this as well, but no luck.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetLink();
}
}
private void SetLink()
{
if (GridView2.Rows.Count == 0)
{
HyperLink1.Visible = true;
}
else
{
HyperLink1.Visible = false;
}
String s = Request.QueryString["language"];
Language1.Text = Server.HtmlEncode(s);
}
protected void Button2_Click(object sender, EventArgs e)
{
SetLink();
}
Any suggestions?
Handle GridView.DataBound event
protected void GridView1_DataBound(object sender, EventArgs e)
{
SetLink();
}
And markup:
<asp:GridView OnDataBound="GridView1_DataBound" ....
Remove the code from the Page_Load event.

Problem with page lifecycle

The qustion was modified by me to show a complete picture.
I have a basic question:
code behind:
protected void Page_Load(object sender, EventArgs e)
{
int firstPageIndex = 0;
int lastPageIndex = 5;
if (TotalPageNumber > 5)
{
if ((TotalPageNumber - PageIndex) <= 5)
firstPageIndex = TotalPageNumber - 5;
firstPageIndex = PageIndex < 3 ? 0 : PageIndex - 2;
}
else
{
firstPageIndex = 0;
lastPageIndex = TotalPageNumber;
}
for (int i = firstPageIndex; i < firstPageIndex + lastPageIndex; i++)
{
LinkButton lnk = new LinkButton();
lnk.CommandArgument = i.ToString();
lnk.Click += new EventHandler(lblPageNumber_Click);
lnk.ID = "lnkPage" + (i + 1).ToString();
lnk.Text = (i + 1).ToString();
plcPagerHolder.Controls.Add(lnk);
} }
int _pageIndex;
public int PageIndex
{
get
{
object objPage = ViewState["_pageIndex"];
if (objPage == null)
{
_pageIndex = 0;
}
else
{
_pageIndex = (int)objPage;
}
return _pageIndex;
}
set {ViewState["_pageIndex"] = value; }
}
protected void lnkPagerNext_Click(object sender, EventArgs e)
{
PageIndex = PageIndex == TotalPageNumber - 1 ? 0 : PageIndex + 1;
}
The problem is with Page_Load event, I expect to get new PageIndex after the linkbutton is clicked.
Update:
My Foo adds new controls to the page, based on provide Page index so I guess I can't put it in Prerender.
Two options
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Foo (PageIndex);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PageIndex = int.Parse(((LinkButton)sender).CommandArgument);
Foo (PageIndex);
}
or
protected void Page_PreRender(object sender, EventArgs e)
{
Foo (PageIndex);
}
you can place Foo (PageIndex) in Page_LoadComplete event instead of Page_Load, i.e.
protected void Page_LoadComplete(object sender, EventArgs e)
{
Foo (PageIndex);
}
LoadComplete event is raised after Control events.
Edit:
LoadComplete is the earliest place where you can safely access new pageindex and also you can add there another controls, but that is possible also in PreRender.
And you will, but Page_Load gets called before the event handler for the linkbutton .. so, you can't really expect it to be changed yet.

Resources