Page Counter not working ASP.NET C# - c#

everybody. I've been trying to follow exactly what it says in my textbook, but to no avail. Now, my problem is that I'm currently attempting to make a page counter to keep track of how many times each page has been accessed, then display each value on a new page.
Here is the C# Counter code which is the same for all pages:
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountMain"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountMain"]);
sessionCount++;
}
protected void Page_PreRender(object sender, EventArgs e)
{
Session["CountMain"] = sessionCount;
}
The prerender is something I added in myself after research on the internet, and in the textbook. No luck.
Here is the Counter Page C# code:
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
string sessionMain = Session["CountMain"].ToString();
string sessionComment = Session["CountComment"].ToString();
string sessionCompleted = Session["CountCompleted"].ToString();
string sessionCurrent = Session["CountCurrent"].ToString();
string sessionAbout = Session["CountAbout"].ToString();
string sessionContact = Session["CountContact"].ToString();
string sessionCounter = Session["CountCounter"].ToString();
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
lblAboutCount.Text = sessionAbout;
lblCommentCount.Text = sessionComment;
lblCompletedCount.Text = sessionCompleted;
lblContactCount.Text = sessionContact;
lblCounterCount.Text = sessionCounter;
lblCurrentCount.Text = sessionCurrent;
lblMainCount.Text = sessionMain;
}
When I try to run it, I get a "NullReferenceException was unhandled by user code, Object reference not set to an instance of an object." Error.
Thanks in advance.
EDIT #1
Okay, Thanks to Hexxangonal, the counter is now working. However, my Counter Page is now counting it self by 2 times. (incrementing by 2 every time it loads)
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountCounter"] == null)
{
sessionCount = 0;
Session["CountCounter"] = sessionCount;
}
else
{
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
Session["CountCounter"] = sessionCount;
}
Session["CountCounter"] = sessionCount;
lblAboutCount.Text = Convert.ToString(Session["CountAbout"]);
lblCommentCount.Text = Convert.ToString(Session["CountComment"]);
lblCompletedCount.Text = Convert.ToString(Session["CountCompleted"]);
lblContactCount.Text = Convert.ToString(Session["CountContact"]);
lblCounterCount.Text = Convert.ToString(Session["CountCounter"]);
lblCurrentCount.Text = Convert.ToString(Session["CountCurrent"]);
lblMainCount.Text = Convert.ToString(Session["CountMain"]);
}

The NullReference exception is probably coming from one of your Session["CountXXXXX"].ToString() lines (CountXXXXX is one of your count objects like CountMain) because Session["CountXXXXX"] does not exist (it is null).
You can actually simplify that page to the following logic and you will bypass the issue as the null will just be assigned to the string variable.
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
// **NEW** Save the new count value
Session["CountCounter"] = sessionCount;
lblAboutCount.Text = Session["CountAbout"];
lblCommentCount.Text = Session["CountComment"];
lblCompletedCount.Text = Session["CountCompleted"];
lblContactCount.Text = Session["CountContact"];
lblCounterCount.Text = sessionCounter;
lblCurrentCount.Text = Session["CountCurrent"];
lblMainCount.Text = Session["CountMain"];
}
There was also an issue where you were mixing integers and strings with the sessionCount variable with a member variable and a local variable (respectively). I have cleaned this up.

The problem is with these two lines
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
You are not putting back these values into the session variable.
You should be doing as follows:-
if (Session["CountCounter"] == null)
{
sessionCount = 0;
Session["CountCounter"]=sessionCount;
}
else
{
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
Session["CountCounter"]=sessionCount;
}

Related

C# search checklistbox on textbox but don't remember checked or copy record twice to checklistbox C#

i have problems with searching checklistbox in textbox. When I have 1 parameter
ladujZBazy(string mustContains)
When I checked items on list in checkedListBox1 and search some items using textBox1 my previous check is gone.
I add 2nd parameter to your function(bool type)
void ladujZBazy(string mustContains, bool dropIndexes)
which will by default be false
private void dbopakowania_Load(object sender, EventArgs e)
{
ladujZBazy(null, false);
}
and And then call textbox's TextChanged event as false.
private void textBox1_TextChanged(object sender, EventArgs e)
{
ladujZBazy(textBox1.Text, false); //false
}
This time checked is not gone but copy record twice to checklistbox.. When value boolean is true I checked items on list in checkedListBox1 and search some items using textBox1 my previous check is gone. I want when i checked and search some items using textBox1 my previous checked is not gone and don't copy record twice to checklistbox.
Full Code:
namespace Email_Sender
{
public partial class dbopakowania : Form
{
EmailSender emailsender;
public List<List<string>> listOpakowaniaTabela = new List<List<string>>();
public string doZamowienia = "";
List<int> indexes = new List<int>();
string typZgloszenia;
public dbopakowania(EmailSender _emailsender, string _typZgloszenia)
{
InitializeComponent();
this.emailsender = _emailsender; //przechwycenie obiektu EmailSender do lokalnego obiektu tego samego typu
this.typZgloszenia = _typZgloszenia;
if (typZgloszenia == "ZWROT")
{
label1.Text = "Zwróć opakowania:";
btnGetItem.Text = "Zwróć";
this.emailsender.txt_subject.Text = "Zwrot opakowań";
}
else if(typZgloszenia == "ZAMOWIENIE")
{
label1.Text = "Zamów opakowania:";
btnGetItem.Text = "Zamów";
this.emailsender.txt_subject.Text = "Zamówienie opakowań";
}
}
private void dbopakowania_Load(object sender, EventArgs e)
{
ladujZBazy(null, false);
}
private void button2_Click(object sender, EventArgs e)
{
if (label1.Text == "Zamów opakowania:")
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
AddValueToZamówienieOpakowan oknoZamowieniaOpakowania_Szczegoly = new AddValueToZamówienieOpakowan(this, indexes[i]);
oknoZamowieniaOpakowania_Szczegoly.ShowDialog();
if (doZamowienia != "")
{
this.emailsender.pozycja++;
this.emailsender.txt_msg.Text += emailsender.pozycja.ToString() + "." + " " + doZamowienia;
//this.emailsender.txt_subject.Clear();
//this.emailsender.txt_subject.Text = "Zamówienie opakowań";
}
}
}
this.Close();
}
else if (label1.Text == "Zwróć opakowania:")
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
ZwrotOpakowan oknoZamowieniaOpakowania_Szczegoly = new ZwrotOpakowan(this, indexes[i]);
oknoZamowieniaOpakowania_Szczegoly.ShowDialog();
if (doZamowienia != "")
{
this.emailsender.pozycja++;
this.emailsender.txt_msg.Text += emailsender.pozycja.ToString() + "." + " " + doZamowienia;
//this.emailsender.txt_subject.Clear();
//this.emailsender.txt_subject.Text = "Zamówienie opakowań";
}
}
}
this.Close();
}
else
{
MessageBox.Show("Nieoczekiwany Błąd - skontaktuj sie z admin", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btn_close_Click(object sender, EventArgs e)
{
this.Close();
}
void ladujZBazy(string mustContains, bool dropIndexes)
{
if (dropIndexes)
{
checkedListBox1.Items.Clear();
listOpakowaniaTabela.Clear();
indexes.Clear();
}
bazaproduktowDBEntities dc = new bazaproduktowDBEntities();
var c1 = from d in dc.OpakowaniaTabela select d.NazwaOpakowania;
var c2 = from d in dc.OpakowaniaTabela select "(" + d.PartiaOpakowania + ")";
var c3 = from d in dc.OpakowaniaTabela select d.IloscOpakowania;
var c4 = from d in dc.OpakowaniaTabela select d.JednostkaOpakowania;
listOpakowaniaTabela.Add(c1.ToList());
listOpakowaniaTabela.Add(c2.ToList());
listOpakowaniaTabela.Add(c3.ToList());
listOpakowaniaTabela.Add(c4.ToList());
for (int i = 0; i < listOpakowaniaTabela[0].Count; i++)
{
string strToAdd = "";
for (int j = 0; j < listOpakowaniaTabela.Count; j++)
{
strToAdd += " " + listOpakowaniaTabela[j][i] + " ";
}
if (mustContains == null)
{
checkedListBox1.Items.Add(strToAdd);
indexes.Add(i);
}
else if (strToAdd.ToLower().Contains(mustContains.ToLower()))
{
checkedListBox1.Items.Add(strToAdd);
indexes.Add(i);
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
ladujZBazy(textBox1.Text, false); //false
}
}
Any Solution? C#

How to Load all the Objects in an Array List

I am trying to figure out how to load through an Array List of Objects. I am able to retrieve the last Object in the Array, but it will not let me Load any other Object after that. here is part of the code I have. As you can see it saves the object to the List, but when I click the loadLastBtn it will only load the most recent entry and if I hit it again after that nothing loads.
List<Members> lstMembers = new List<Members>();
private int hold;
private void submitBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(firstNameTxt.Text) || string.IsNullOrEmpty(lastNameTxt.Text)
|| string.IsNullOrEmpty(userNameTxt.Text) ||
string.IsNullOrEmpty(passwordTxt.Text) || string.IsNullOrEmpty(confPassTxt.Text)
|| string.IsNullOrEmpty(majorBox.Text) || string.IsNullOrEmpty(specialtyBox.Text))
{
MessageBox.Show("You must enter in all fields before moving forward");
}
else
{
Members m1 = new Members(firstNameTxt.Text, lastNameTxt.Text, userNameTxt.Text,
passwordTxt.Text, confPassTxt.Text, majorBox.Text,
specialtyBox.Text);
lstMembers.Add(m1);
}
}
private void loadLastBtn_Click(object sender, EventArgs e)
{
firstNameTxt.Text = lstMembers[hold].FirstName;
lastNameTxt.Text = lstMembers[hold].LastName;
userNameTxt.Text = lstMembers[hold].UserName;
passwordTxt.Text = lstMembers[hold].Password;
confPassTxt.Text = lstMembers[hold].ConfPassword;
majorBox.Text = lstMembers[hold].Major;
specialtyBox.Text = lstMembers[hold].Specialty;
hold++;
}
I have edited my answer. this will now print each user one by one each time I hit loadLastBtn, but it does show them from the first user to the last, where I need it to shower the last user to the first.
What you need is something like this:
// -1 Indicates that you should start at the end of the list
int index = -1;
private void loadButton_Click(object sender, EventArgs e)
{
if (members != null && members.Count > 0) // Avoid accessing if list is empty or null
{
if (index == -1)
index = members.Count - 1;
firstNameTxt.Text = lstMembers[index].FirstName;
lastNameTxt.Text = lstMembers[index].LastName;
userNameTxt.Text = lstMembers[index].UserName;
passwordTxt.Text = lstMembers[index].Password;
confPassTxt.Text = lstMembers[index].ConfPassword;
majorBox.Text = lstMembers[index].Major;
specialtyBox.Text = lstMembers[index].Specialty;
if (index == 0) // Reached beginning of array
index = -1; // Indicate that next time the last element must be accessed
else
--index;
}
}
private int hold = lstMembers.Count -1;
private void loadLastBtn_Click(object sender, EventArgs e)
{
firstNameTxt.Text = lstMembers[hold].FirstName;
lastNameTxt.Text = lstMembers[hold].LastName;
userNameTxt.Text = lstMembers[hold].UserName;
passwordTxt.Text = lstMembers[hold].Password;
confPassTxt.Text = lstMembers[hold].ConfPassword;
majorBox.Text = lstMembers[hold].Major;
specialtyBox.Text = lstMembers[hold].Specialty;
hold--;
}

C#, How to get HTML generated textbox values during foreach Control loop and then show the result?

Behind the code C#, when the user select 3(dropdownlist) then press execute button, it will auto generate 3 textboxes. After user fill out names on 3 textboxes then click request button, I want the 3 names that user entered display on different result textbox. How do I do that?
Here are C# codes,
protected void ExecuteCode_Click(object sender, EventArgs e)
{
int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
for (int num = 1; num <= amount; num++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(t);
div1.Controls.Add(div);
}
ButtonRequest.Visible = true;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
string str = "";
foreach (Control c in phDynamicTextBox.Controls)
{
try
{
TextBox t = (TextBox)c;
// gets textbox ID property
//Response.Write(t.ID);
str = t.Text;
}
catch
{
}
}
TextBoxFinal.Text = str;
}
Then HTML codes,
<div id="div1" runat="server">
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
</div>
you cannot access to control that create dynamically on postback, but you can try get input value from request like this
protected void ExecuteCode_Click(object sender, EventArgs e)
{
List<string> tbids = new List<string>();
int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
for (int num = 1; num <= amount; num++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(t);
phDynamicTextBox.Controls.Add(div);
tbids.Add(t.ID);
}
Session["tbids"] = tbids;
ButtonRequest.Visible = true;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
string str = "";
var tbids = (List<string>)Session["tbids"];
foreach (var id in tbids)
{
try
{
str += Request[id]+" "; //here get value tb with id;
}
catch
{
}
}
TextBoxFinal.Text = str;
}
One option is:
when you create the textbox you save the Id in a list in session, then you through the list and use it:
TextBox myTextbox = (TextBox)FindControl("name");
example:
List<string> list = (List<string>)Session["myList"];
TextBox myTextbox;
foreach (string item in list)
{
myTextbox = (TextBox)FindControl(item);
//in myTextbox you have the atribute Text with the informatcion
}
Sorry for my english.

How do I define a variable for use everywhere

According to below code , after getting some value (newrev,newreview) and putting in the variable, I need to put them in the label ("some text"+newrev). But I have problem (newrev) does not exist in current context.
Label1.Text = "Review Number:" + newReview + "(for preparing of Rev." + newrev+")";
protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var x = ddlProjectDocument.SelectedValue;
var MaxRev = (from rev in _DataContext.tblTransmittalls
where rev.DocID.ToString() == ddlProjectDocument.SelectedValue
select rev.REV).Max();
if (MaxRev == null)
{
var newRev = 0;
}
else
{
var newRev = Convert.ToInt32(MaxRev) + 1;
}
var MaxReview = (from rev in _DataContext.tblFiles
where (rev.DocId.ToString()==ddlProjectDocument.SelectedValue)&&
(rev.Rev.ToString()==MaxRev)
select rev.Review).Max();
if (MaxReview == null)
{
var newReview = 1;
}
else
{
var newReview = Convert.ToInt32(MaxReview) + 1;
}
Label1.Text = "Review Number:" + newReview + "(for preparing of Rev." + newrev+")";
}
Define newRev and newReview in the begining of your function like this:
protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
int newRev;
int newReview;
Then when you want to use them, instead of writing var newReview = ... (which declares a new variable) remove the var... e.g.:
if (MaxReview == null)
{
newReview = 1;
}
The difference:
Every variable that is declared has a Scope, which determines its visibility to the rest of a program. In your case, the newReview is known only inside the if statement, so when you try to reference it outside, it no longer exists.
You need to declare newRev outside the if statement.
int newrev;
if(MaxRev == null)
newRev = 0;
else
newRev = Convert.ToInt32(MaxRev) + 1;
C# is not JavaScript, you should use less "var"...
You are defining your newRev inside
if (MaxRev == null)
{
var newRev = 0;
}
define it here
protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var newRev = 0;
....
}
it's because you're declaring newRev within various if statements, declare it at the outer level:
int newRev;
if (MaxRev == null)
{
newRev = 0;
}

Remove items from DropDownList

I have two DropDownLists one for the type of a soldier and one for the number of soldiers the player i allowed to buy. I populate ddlSoldiers with a LinqDataSource in the aspx page like this:
<asp:DropDownList ID="ddlSoldiers" runat="server"
DataSourceID="LinqDataSource2" DataTextField="type"
DataValueField="troopid" AutoPostBack="True">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="BrowserSpill.LinqClass1DataContext" EntityTypeName=""
Select="new (type, troopid)" TableName="Troops">
</asp:LinqDataSource>
The other list ddlSoldierNumber is populated in the pageload like this:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userRole"] == null || Session["userRole"].Equals("admin"))
{
Response.Redirect("Login.aspx");
}
int userid = Convert.ToInt32(Session["userid"]);
if(string.IsNullOrEmpty(ddlSoldiers.SelectedValue))
{
var varTroopType = dc.Troops.Single(t => t.troopid == 1).type;
string troopType = Convert.ToString(varTroopType);
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
else
{
ddlSoldierNumber.Items.Clear();
string troopType = ddlSoldiers.SelectedItem.Text;
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for(int i = 1; i < numberOfBuildings+1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
}
But when i want to get the values from ddlSoldierNumber i only get the first value in that list. I try to get the number with the click of a button like this:
protected void btnBuySoldier_Click(object sender, EventArgs e)
{
string numbertobuy = ddlSoldierNumber.SelectedItem.Value;
lblAntall.Text = numbertobuy;
}
I have tried to put the line:
ddlSoldierNumber.Items.Clear();
other places but without any luck. Does anyone know how i can clear the number list after I press the button and before the ddlSoldierNumber get repopulated?
if you want to populate ddlSoldierNumber on the basis of selection from ddlSoldiers then you can not add values to ddlSoldierNumber in page load event. for that you have to add your page load event code in (ddlSoldiers) selected index change event.
protected void ddlSoldiers_SelectedIndexChanged(object sender, EventArgs e)
{
if (Session["userRole"] == null || Session["userRole"].Equals("admin"))
{
Response.Redirect("Login.aspx");
}
int userid = Convert.ToInt32(Session["userid"]);
if (string.IsNullOrEmpty(ddlSoldiers.SelectedValue))
{
var varTroopType = dc.Troops.Single(t => t.troopid == 1).type;
string troopType = Convert.ToString(varTroopType);
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
else
{
ddlSoldierNumber.Items.Clear();
string troopType = ddlSoldiers.SelectedItem.Text;
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
}
If I remember correctly, the pageload is run before your eventhandler for the button, have you tried placing the ddlSolderNumber.Items.Clear(); in the Click eventhandler after you change the label?
(I know this doesnt solve the issue with your first question)
For that you could try: (If Im confusing I apologize, Im bad at explaining myself)
You could create a "populate" method for your ddlSoldierNumber list, that you call after your click-event.
In your pageload, you could then on a check of "if (!PostBack)" run your default startup logic.

Categories