How to Load all the Objects in an Array List - c#

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--;
}

Related

How can I automatically update column in datagridview base on the other column input

I have a datagridview dgvBlood and I have 4 columns Result, RangeFrom, RangeTo, Status. I just want to have a Status to be Normal or Abnormal based on the input in Result. If Result >= RangeFrom && Result <= RangeTo then Result = "Normal" else "Abnormal" RangeFrom and RangeTo is already given. User will just input Result and I just want to update it once the user has input.
Here's my sample code. And any help is appreciated.
private void dgvBlood_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
Double From = Convert.ToDouble(dgvBlood.CurrentRow.Cells["RangeFrom"].Value.ToString());
Double To = Convert.ToDouble(dgvBlood.CurrentRow.Cells["RangeTo"].Value.ToString());
Double Result = Convert.ToDouble(dgvBlood.CurrentRow.Cells["Result"].Value.ToString());
String value = "Normal";
String valueAb = "Abnormal";
if (Result >= From && Result <= To)
{
dgvBlood.CurrentRow.Cells["Status"].Value = value;
}
else
{
dgvBlood.CurrentRow.Cells["Status"].Value = valueAb;
}
}
Try following
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
Double From = Convert.ToDouble("0"+dataGridView1.CurrentRow.Cells["RangeFrom"].Value);
Double To = Convert.ToDouble("0" + dataGridView1.CurrentRow.Cells["RangeTo"].Value);
Double Result = Convert.ToDouble("0" + dataGridView1.CurrentRow.Cells["Result"].Value);
if (Result >= From && Result <= To)
{
dataGridView1.CurrentRow.Cells["Status"].Value = "Normal";
}
else
{
dataGridView1.CurrentRow.Cells["Status"].Value = "Abnormal";
}
}
You will have to put in a condition to check on which column change, status should change. Currently it will check for change in any cell.

Check if the selected item in a listbox contains specific characters

I am trying to figure out how to check if a listbox contains a specific string at a selected index, but i can't figure it out. It's an WAF project.
private void UpdateGUI(string name, double price)
{
//Check if the seat is already reserved??
//Check if the seat is already canceled??
int index = lstSeats.SelectedIndex;
if (index < 0)
{
MessageBox.Show("Please select an item in the list!");
return;
}
string strOut = string.Empty;
string strReserved = "Vacant";
if (rbtnReserve.Checked)
{
strReserved = "Reserved";
}
else
{
name = string.Empty;
price = 0.0;
}
strOut = string.Format("{0,3} {1,14} {2,11} {3,13:f2}", index + 1, strReserved, name, price);
lstSeats.Items.RemoveAt(index);
lstSeats.Items.Insert(index, strOut);
lblNumOfReservedSeats.Text = numOfReservedSeats.ToString();
lblNumberOfVacantSeats.Text = (totalNumOfSeats - numOfReservedSeats).ToString();
lblTotalNumOfSeats.Text = totalNumOfSeats.ToString();
}
Basically, i don't want to reserve a seat (in the cinema) that already has been reserved, or if the seat already is cancelled, i don't want to cancel it again. Any suggestions?
Or would it be better to check in the following code?:
private void btnOK_Click(object sender, EventArgs e)
{
string name = string.Empty;
double price;
bool inputOK = ReadAndValidateInput(out name, out price);
if (inputOK)
{
if (rbtnReserve.Checked)
{
numOfReservedSeats++;
}
else
{
numOfReservedSeats--;
}
UpdateGUI(name, price);
}
}
EDIT:
for WFA and checking if an item contains given string use this:
if (listBox1.SelectedIndex != -1)
{
int itemAtPostion = listBox1.SelectedIndex;
string reserved = "Reserved";
if (listBox1.Items[itemAtPostion].ToString().Contains(reserved))
{
MessageBox.Show("We are sorry, but this seat is reserved!");
//your code
}
}
You can use this one. It's so simple
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each i In ListBox1.Items
If i.ToString.Contains("your specific characters") Then
//what happen if it true
Else
//what happen if it false
End If
Next
//what happen when its finish work
End Sub
You can also use C#:
private void Button1_Click(object sender, EventArgs e)
{
foreach (var i in ListBox1.Items)
{
if (i.ToString().Contains("your specific characters"))
{
//what happen if it true
}
else
{
//what happen if it false
}
}
//what happen when its finish work
}

Page Counter not working ASP.NET 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;
}

ListBox Selection keeps looping

When I select an item from my list, the whole selection-process goes on twice.
private void serving_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
Debug.WriteLine("Serving added to diary");
login(null, null);
}
catch (WebException)
{
Debug.WriteLine(e.Error);
}
ServingList.SelectedIndex = -1;
}
When I leave out ServingList.SelectedIndex = -1; the process goes on once. But I need the selected index back to -1.
What am I missing?
Handler on SelectionChanged:
private void ServingList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Debug.WriteLine("\n[#] ServingList_SelectionChanged");
Debug.WriteLine("Selected item:" + ServingList.SelectedIndex);
Debug.WriteLine("ID of latest TP: " + tp.id);
String itemid = tp.id;
Produkt temp = (Produkt)ServingList.SelectedItem;
if (servingid.Length < 1)
{
servingid = temp.servingid;
}
WebClient addserving = new WebClient();
addserving.Credentials = new NetworkCredential(username.Text, passwort.Password);
addserving.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
addserving.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
addserving.UploadStringAsync(new Uri("http://fddb.info/api/v8/diary/add_item.xml?apikey=ICPOKUI83555PU43"), "&item_id=" + itemid + "&serving_id=" + servingid);
addserving.UploadStringCompleted += new UploadStringCompletedEventHandler(serving_UploadStringCompleted);
Pivot.SelectedIndex = 0;
}
You are causing an infinate loop.
You have your list box and changing it causes an action
Change X > Action X > Handle X > Change X (-1) > Action X
Etc.
You need to have some form of break to the loop for a condition
private void serving_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
//Break condition
if (ServingList.SelectedIndex != -1)
{
try
{
Debug.WriteLine("Serving added to diary");
login(null, null);
}
catch (WebException)
{
Debug.WriteLine(e.Error);
}
ServingList.SelectedIndex = -1;
}
}
By doing this, you only set it to -1 when you need to, otherwise it will continuously keep setting the selected index to -1 even though it is already in fact set.

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