How to put an object list into an asp:literal? - c#

I have a class and have added objects to a list, then binded the list to a checkboxlist. When the user checks the list, the answer goes into a new list and put in a session, then redirected to a new page. On the new page I want the result in an asp:Literal. But Im not sure how to do that.
The class:
public class Frukter
{
public string Navn { get; set; }
public string Farge { get; set; }
public string BildeSrc { get; set; }
public Frukter(string navn, string farge, string bildeSrc)
{
Navn = navn;
Farge = farge;
BildeSrc = bildeSrc;
}
}
First page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Frukter> frukt = new List<Frukter>();
frukt.Add(new Frukter("Appelsin", "Oransj", "~/Appelsin.jpg"));
frukt.Add(new Frukter("Banan", "Gul", "~/Banan.jpg" ));
frukt.Add(new Frukter("Eple", "Rød", "~/Eple.jpg" ));
if (!this.IsPostBack)
{
chklst.DataSource = frukt;
chklst.DataTextField = "Navn";
chklst.DataBind();
}
protected void Resultat_Click(object sender, EventArgs e)
{
List<object> ChkListe = new List<object>();
foreach (ListItem item in chklst.Items)
{
if(item.Selected)
// If the item is selected, add the value to the list.
ChkListe.Add(item);
}
Session["selectedChkList"] = ChkListe;
Response.Redirect("Default2.aspx", false);
}
}
Second page where I take the list out of session, but not sure how to get it into the asp:literal.
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<object> ResultatList = new List<object>();
if (Session["selectedChkList"] != null)
{
ResultatList = (List<object>)Session["selectedStrList"];
ResultatLliteral.Text = String.Format("<p>{0} {1}</p> <img src ={3} />", Frukter.Navn, Frukter.farge, Frukter.BildeSrc);
}
}
}
}

Some critique on your code and some different approaches, not sure what your assignment is but I'll provide feedback that may be beneficial for your course.
public class Fruit
{
public Fruit(string name, string color, string image)
{
Name = name;
Color = color;
Image = image;
}
public string Name { get; }
public string Color { get; }
public string Image { get; }
}
You defined a Constructor that will always set a value upon creation, so unless you intend to modify the object after the fact you can set your properties to read only.
Personally I would use a database or another way to persist my data, but for your example you should be able to do the following:
var fruits = new List<Fruit>()
{
new Fruit("Apple", "Red", "..."),
new Fruit("Grapefuit", "Yellow", "...")
};
// Grab the selected checkbox in the checkbox list item (You'll have to see if a collection is returned or not)
var selectedFruit = chkLFruit.Items.Cast<ListItem>().Where(item => item.Selected);
// Take selected item and pass full object into session.
var filter = fruits.Where(fruit => selectedFruit.Select(t => t.Text).FirstOrDefault(x => String.Compare(x, fruit.Name, true) == 0);
// Create Session
HttpContext.Session["FruitSelection"] = filter;
On your other page before you attempt to use simply do the following:
var selectedFruits = (List<Fruit>)HttpContext.Session["FruitSelection"];

Related

How to make a listbox display items from a checked list and radio buttons? - C# Windows Form

I'm doing a project where I am trying to simulate an ice cream parlor. For this specific section, I have the (mutually exclusive) radio buttons representing the dressing the customer can select. There are also a number of checked items (not mutually exclusive) which the customer can select in the checkedListBox. All of the items that a customer selects from the radio buttons and checkedListBox are supposed to appear in a listbox. so that the customer can keep track of all of the ordered items.
Of course, all of the code here is very unfinished and basic. I don't plan on adding any of the calculations for the prices until I make sure that the structure itself is working.
This is what I currently have so far:
private void GetToppings()
{
foreach (ListViewItem li in checkedListBox1.Items)
{
if (li.Selected == true)
{
label1.Text += li + " ";
}
}
if (checkedListBox1.SelectedItem.ToString() == "Sprinkles")
{
}
if (checkedListBox1.SelectedItem.ToString() == "Chocolate Chips")
{
}
if (checkedListBox1.SelectedItem.ToString() == "M&Ms")
{
}
if (checkedListBox1.SelectedItem.ToString() == "Oreos")
{
}
if (checkedListBox1.SelectedItem.ToString() == "Cookie Dough")
{
}
private void GetDressing()
{
if (radioButton1.Checked)
{
sDressing += "Caramel";
}
if (radioButton2.Checked)
{
sDressing += "Hot Fudge";
}
if (radioButton3.Checked)
{
sDressing += "Peanut Butter";
}
if (radioButton4.Checked)
{
sDressing += "Strawberry Syrup";
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i<18; i++)
{
listBox1.Items.Add(i);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
I am still very new to Windows Form programming in C#, so please forgive me if any of these questions/errors seem very basic.
The RadioButton use the following
var radioButton = Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
if (radioButton is not null)
{
// do something
}
For the CheckedListBox consider the following which populates via a model/class which has text and a identifier as in most cases at a later date you work with a data source this is important to keep track of items which you are not there yet but best to do it just the same.
Extension method to get items in the CheckedListBox. Place in a class file.
public static class CheckedListBoxExtensions
{
public static List<T> CheckedList<T>(this CheckedListBox sender)
=> sender.Items.Cast<T>()
.Where((_, index) => sender.GetItemChecked(index))
.Select(item => item)
.ToList();
}
Use a class/model for populating the CheckedListBox, ToString is used to display the item. Place in a class file.
public class Topping
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString() => Name;
}
Implementation
public partial class StackOverflowForm : Form
{
public StackOverflowForm()
{
InitializeComponent();
List<Topping> toppings = new List<Topping>
{
new Topping() { Id = 1, Name = "Sprinkles" },
new Topping() { Id = 2, Name = "Chocolate Chips" },
new Topping() { Id = 3, Name = "M&Ms" },
new Topping() { Id = 4, Name = "Oreos" },
new Topping() { Id = 5, Name = "Cookie Dough" }
};
checkedListBox1.DataSource = toppings;
}
private void GetToppingsButton_Click(object sender, EventArgs e)
{
List<Topping> toppings = checkedListBox1.CheckedList<Topping>();
if (toppings.Count > 0)
{
listBox1.DataSource = toppings;
}
else
{
listBox1.DataSource = null;
}
}
}

Update a List<t> object and his properties

I have a list MemoryClienti with items based on the ClienteModel class.
The method i use to add a new item to MemoryClienti is:
public bool CreateCliente(ClienteModel model)
{
bool empty = !MemoryClienti.Any();
if (empty)
{
ClienteModel clienteModel = new ClienteModel();
clienteModel.Cognome = model.Cognome;
clienteModel.Nome = model.Nome;
clienteModel.Indirizzo = model.Indirizzo;
clienteModel.IDCliente = StartID;
MemoryClienti.Add(clienteModel);
MessageBox.Show("Cliente aggiunto correttamente.");
}
else
{
int maxID = MemoryClienti.Count;
ClienteModel clienteModel = new ClienteModel();
clienteModel.Cognome = model.Cognome;
clienteModel.Nome = model.Nome;
clienteModel.Indirizzo = model.Indirizzo;
clienteModel.IDCliente = maxID;
MemoryClienti.Add(clienteModel);
MessageBox.Show("Cliente aggiunto correttamente.");
}
return true;
This method makes me able to add a new item, count for the number of items in the list, and set the new item's id as the result of the count, so it happpens for every item i add, and it's working.
Datas for item's "model" comes from form's textboxes:
private void aggiungiClienteButton_Click(object sender, EventArgs e)
{
if (cognomeTextBox.Text == "")
{
MessageBox.Show("Uno o più campi sono vuoti");
}
else if (nomeTextBox.Text=="")
{
MessageBox.Show("Uno o più campi sono vuoti");
}
else if (indirizzoTextbox.Text == "")
{
MessageBox.Show("Uno o più campi sono vuoti");
}
else
{
clienteModel.Cognome = cognomeTextBox.Text;
clienteModel.Nome = nomeTextBox.Text;
clienteModel.Indirizzo = indirizzoTextbox.Text;
dbMemoryManager.CreateCliente(clienteModel);
cognomeTextBox.Text = String.Empty;
nomeTextBox.Text = String.Empty;
indirizzoTextbox.Text = String.Empty;
}
}
My class is:
public class ClienteModel
{
public int IDCliente { get; set; }
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
}
The problem is: how can i update one of those items using textboxes without changing the id?
Here's a quick and dirty solution. You don't specify what kind of textboxes you are using. I'm assuming it's Windows Forms.
I modified your ClienteModel so that it looks like this:
public class ClienteModel
{
private static int _currentId = 0;
public int IDCliente { get; set; } = _currentId++;
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
public override string ToString()
{
return Nome;
}
}
Note that it manages the IDCliente field now and that it has a ToString member (you can set this to whatever string you want). You may want to show the IDCliente field in a read-only textbox on your form.
Then I created a simple Windows Forms form that has your three text boxes, a ListBox named ModelsListBox and two buttons AddButton (caption: "Add") and UpdateButton ("Update").
In the form class I created a little validation method (since I use it in two places). Note that you will only get one MessageBox even if you have multiple errors:
private bool ValidateFields()
{
var errors = new List<string>();
foreach (var tb in new[] {cognomeTextBox, nomeTextBox, indirizzoTextbox})
{
if (string.IsNullOrWhiteSpace(tb.Text))
{
errors.Add($"{tb.Name} must not be empty");
}
}
if (errors.Count > 0)
{
MessageBox.Show(string.Join(Environment.NewLine, errors), "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
//otherwise
return true;
}
Then I added three event handlers (wiring them up in the normal fashion from within the designer). The first is when the Add button is pressed:
private void AddButton_Click(object sender, EventArgs e)
{
if (!ValidateFields())
{
return;
}
var model = new ClienteModel
{
Cognome = cognomeTextBox.Text,
Nome = nomeTextBox.Text,
Indirizzo = indirizzoTextbox.Text,
};
ModelsListBox.Items.Add(model);
}
It creates a new ClienteModel and adds it to the listbox (assuming validation passes).
Then, I created a handler that updates the text boxes whenever the selection in the listbox changes:
private void ModelsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ModelsListBox.SelectedItem is ClienteModel model)
{
cognomeTextBox.Text = model.Cognome;
nomeTextBox.Text = model.Nome;
indirizzoTextbox.Text = model.Indirizzo;
}
}
and finally, an update button handler:
private void UpdateButton_Click(object sender, EventArgs e)
{
if (!ValidateFields())
{
return;
}
if (ModelsListBox.SelectedItem is ClienteModel model)
{
model.Cognome = cognomeTextBox.Text;
model.Nome = nomeTextBox.Text;
model.Indirizzo = indirizzoTextbox.Text;
}
}
This isn't perfect. You should disable the Update button until a selection is made (and maybe enable only after a change is made in the text box).
More importantly, the string shown in the listbox for an item is based on the results of a call to ClienteModel.ToString made when the item is first added to the list. If you change the value of a field that is used to compute .ToString, the listbox doesn't update. There are a few ways around this (findable on Stack Overflow), but I thought this would be enough to get you started.

Change value in a list that is binded?

I'm pretty new at this. Using Windows Forms in Visual Studio. I am to hammer out a store that has clothes, with stock that can be transferred in or out of the store.
I've gotten as far as to having a class, a list that contains the clothes and their quantities, and I've managed to get them into comboboxes. What I want to do now is to be able to 'buy' new quantities, changing the value in the list.
I'm stumped as to how to change the actual quantities, I'm sure I am missing stuff here.
This is my class:
public class Store
{
public string Clothing { get; set; }
public int Quantity { get; set; }
public Store(string c, int q)
{
Clothing = c;
Quantity = q;
}
And this is my current code:
}
public partial class Form1 : Form
{
List<Store> stock = new List<Store>
{
new Store ("Jeans size S", 1),
new Store ("Jeans size M", 3),
new Store ("Jeans size L", 5)
};
public Form1()
{
InitializeComponent();
}
private void bShow_Click(object sender, EventArgs e)
{
cbStockType.ValueMember = "Clothing";
cbStockType.DisplayMember = "Clothing";
cbStockType.DataSource = stock;
cbStockQnt.ValueMember = "Quantity";
cbStockQnt.DisplayMember = "Quantity";
cbStockQnt.DataSource = stock;
}
private void lblHighlightAdd_Click(object sender, EventArgs e)
{
}
private void bSlctClothing_Click(object sender, EventArgs e)
{
if (cbStockType.SelectedIndex < 0)
{ lblHighlightAdd.Text = "None"; }
else
lblHighlightAdd.Text = cbStockType.SelectedValue.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string quantityToAdd = tbQntAdd.Text;
int add = Convert.ToInt32(quantityToAdd);
string addToStock = cbStockQnt.SelectedValue.ToString();
int newAmount = Convert.ToInt32(addToStock);
int result = newAmount + add;
foreach (var item in stock)
{
if (item.Clothing == cbStockType.SelectedValue.ToString())
{
item.Quantity = item.Quantity + result;
MessageBox.Show(cbStockQnt.SelectedValue.ToString());
}
}
}
}
}
If you can read this spaghetti junk, I'm stuck at getting the quantity of the selected piece of clothing to change. How do I get it to change the value both in the list and in the combobox?

C# Class Can't Use for Azure?

I am new to the windows azure world, I am trying to send an item to the SQL DB and track it by a specific "usrID" to then hopefully update it.
Right now I also have a class:
public class Item
{
public int Id { get; set; }
[JsonProperty(PropertyName = "url")]
public string url { get; set; }
[JsonProperty(PropertyName = "usrID")]
public string usrID { get; set; }
[JsonProperty(PropertyName = "complete")]
public bool Complete { get; set; }
}
To save/insert Data I use:
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
var todoItem = new Item { usrID = "helloworld", url = Input.Text };
InsertTodoItem(todoItem);
}
When I am trying to update, I am using this:
private void btns_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
Item item;
item = new Item();
item.url = "hello";
UpdateItem(item);
}
* Trying to do this will not work. It also wont let me do Item item = new Item();
The update function is:
private async void UpdateItem(Item item)
{
await todoTable.UpdateAsync(item);
items.Remove(item);
}
So, what I am trying to do is, the last/only item inserted by "usrID" to get that data and show it. But also if something changes, I want that one specific insert from "usrID" that includes url to be updated (opposed from deleted entirely).
Any help would be great!
List<Item> items = await App.MobileService.GetTable<Item>().OrderBy(item => item.usrID).ToListAsync();
int mas = items.Count();
await Table.UpdateAsync(new Item {Id = mas, usrID = "helloworld", url = "itworked" });

ASP.NET: How to get values from a selected row from GridView control

I have added a GridView control on my ASP.net webpage and data bound it to a List<> the list contains a collection of a simple custom objects which is defined as:
public class PersonRecord
{
public int PersonId { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Notes { get; set; }
}
I have set AutoGenerateSelectButton to true and and attached an event handler to the SelectedIndexChanged event. I can see my event handler fires and I can get the selected row index by using MyGridView.SelectedIndex.
My question is: how do I use the selected row index to get the PersonId for the selected record?
I thought MyGridView.Rows[MyGridView.SelectedIndex].Cells[0] would do it but it doesn't because MyGridView.Rows.Count is 0.
TIA
Just because I have not played with web applications in awhile, I decided to see if this was something I could dupe. Alas, to no avail. This works fine for me:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
var persons = CreatePersons();
GridView1.DataSource = persons;
GridView1.DataBind();
}
}
private List<PersonRecord> CreatePersons()
{
var person = new PersonRecord
{
PersonId = 1,
Name = "greg",
Title = "Supreme Coder",
Description = "Nada",
Notes = "foo bar"
};
var person2 = new PersonRecord
{
PersonId = 2,
Name = "Sam",
Title = "Junior Coder",
Description = "Nada",
Notes = "foo bar"
};
var list = new List<PersonRecord> {person, person2};
return list;
}
protected void Button1_Click(object sender, EventArgs e)
{
var row = GridView1.Rows[0];
var cell = row.Cells[1];
var value = cell.Text;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
var row = GridView1.Rows[index];
var nameCell = row.Cells[2];
var name = nameCell.Text;
Label1.Text = name;
}
}
Yours most likely fails as you are selecting the select column (cell[0]), but I would think you should get something out of this cell (have to play with it). It could also be a bad pattern for binding.
How are you storing the data from your GridView on the server (session, viewstate, or are you not doing so?). Since you have the selected row index, you just need to get your datasource again. If you persist it in session, then you can just get that session object and get find the object at the index the user selected.

Categories