I'm trying to populate a DropDownList with a List that a user makes. A user types a ball name and its weight and is then added on a list box. In the Default page I have:
List<Ball> myBall;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myBall = new List<Ball>();
Session["listSession"] = myBall;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
Ball f = new Ball(TbxName.Text, int.Parse(TbxWeight.Text));
myBall= (List<Ball>)Session["listSession"];
myBall.Add(f);
foreach (var item in myBall)
{
ListBox1.Items.Add(item.getBallInfo());
}
and in my Ball Class:
public Ball(string n, int w)
{
name = n;
weight = w;
}
public string getBallInfo()
{
string s;
if (weight > 5)
{
s = name + " is huge"
}
else
{
s = name + " is small"
}
How can I, in another class with a DropDownList, populate it with the Ball names from default class?
The same way you do it with the ListBox - in fact, the two are almost identical in HTML.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack && Session["listSession"] != null)
{
var myBall = (List<Ball>)Session["listSession"];
foreach (var ball in myBall)
DropDownList1.Items.Add(item.getBallInfo());
}
}
Related
I have two asp.net pages and the summary.aspx will be called from the first asp.net page by using Response.Redirect("summary.aspx").
Ticket is a custom class with 4 attributes (String name, int age, int seat, int price), their getter and setters and a ToString method.
Session["tickets"] stores the objects of Ticket class
My Problem is that I have a dropdownlist called drop_remove and a button called btn_remove. When I click the button, it should remove the selected item and remove the corresponding object from List<Ticket> tickets. However, it always remove the top item from the dropdownlist. I am new to asp.net, please help.
public partial class summary : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Ticket> tickets = (List<Ticket>)Session["tickets"];
if (Session["eventName"].ToString() != null)
{
label_event.Text = Session["eventName"].ToString();
}
if (tickets != null)
{
displayTickets(tickets);
}
if (Session["tickets"] == null)
{
tickets = new List<Ticket>();
}
else
{
tickets = (List<Ticket>)Session["tickets"];
drop_remove.Items.Clear();
foreach (Ticket a in tickets)
{
drop_remove.Items.Add(a.name.ToString());
}
}
}
protected void moreTicekts_Click(object sender, EventArgs e)
{
Response.Redirect("default.aspx");
}
private void displayTickets(List<Ticket> tickets)
{
TextBox1.Text = "";
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append(Environment.NewLine);
foreach (Ticket a in tickets)
{
builder.Append(a.ToString() + Environment.NewLine);
}
TextBox1.Text += builder.ToString();
}
protected void btn_remove_Click(object sender, EventArgs e)
{
List<Ticket> tickets = (List<Ticket>)Session["tickets"];
for (int i = 0; i < tickets.Count; i++)
{
if (tickets[i].name.Equals(drop_remove.SelectedItem.ToString()))
{
drop_remove.Items.Remove(drop_remove.SelectedItem);
tickets.RemoveAt(i);
break;
}
}
Session["tickets"] = null;
Session["tickets"] = tickets;
}
}
The problem is that on every postback you clear out drop_remove inside Page_Load. As the result, the selected item was removed from the list since every item is recreated again. Then, top item becomes selected item by default.
As Wael Abbas said, you need to place those code inside if (!IsPostBack).
public partial class summary : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Ticket> tickets = (List<Ticket>)Session["tickets"];
// the rest of the code here
}
}
...
}
I am using Asp.net(C#), and SQL Server. In web application I want 5 digit Invoice number in text box, and after clicking on button the gridviews data to be saved in database, and then invoice number in the text box should be increment by one...and so on. I used this code =>
protected void Page_Load(object sender, EventArgs e)
{
double ID = 00001;
txtinvoiceno.Text = Convert.ToString(ID);
and
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = Convert.ToString(no);
}
but it shows in the output only single digit 1, and increment it only once time i.e.2, and further increment is not working.
Anyone have any idea on this??
Thanks & Regards,
I doubt this will even compile, as within btnsavef1_Click the variable ID is not defined. You probably want ID to be an instance-variable:
class MyClass {
private int ID = 0;
protected void Page_Load(object sender, EventArgs e)
{
txtinvoiceno.Text = this.ID.ToString("D5");
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
this.ID++;
txtinvoiceno.Text = this.ID.ToString("D5");
}
}
Furthermore you won´t actually store the formatted number. Simply store the number as integer and do the formatting within your events-code using ToString and format-specifiers.
Try this :
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int ID = 1;
txtinvoiceno.Text = ID.ToString("D5");
}
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
int ID = Convert.ToInt16(txtinvoiceno.Text );
ID++;
txtinvoiceno.Text = ID.ToString("D5");
}
}
You´re looking for formatting, which is very easy in your case:
//DONE: int, not double - do you want to deal with round-up errors?
//DONE: ID should be a field, not a local variable
private int ID = 0;
protected void Page_Load(object sender, EventArgs e)
{
// whenever you want 5 digits - just put 5 zeroes when formatting
txtinvoiceno.Text = ID.ToString("00000");
...
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID += 1;
// once again: want 5 digits - put 5 zeroes when formatting
txtinvoiceno.Text = ID.ToString("00000");
}
A better choice, IMHO, is to convert ID into property and hide formatting there:
private int m_ID;
public int ID {
get {
return m_ID;
}
set {
m_ID = value;
txtinvoiceno.Text = m_ID.ToString("00000");
}
}
...
protected void Page_Load(object sender, EventArgs e) {
// Just assign
ID = 0;
...
}
protected void btnsavef1_Click(object sender, EventArgs e) {
// Just increment
ID += 1;
}
Try this :
public partial class Form2 : Form
{
private double ID=0;
public Form2()
{
InitializeComponent();
}
protected void Page_Load(object sender, EventArgs e)
{
double ID = 00001;
txtinvoiceno.Text = Strings.Format(ID, "000000")
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = Strings.Format(no, "000000")
}
}
you need to format only result number after increment.
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = no.ToString().PadLeft(5, '0');
}
if ID=7
your result will be after Increment
will be 00008
I want to remove an item from a list...
I am obviously missing something...I have tried just about every variation including EXCEPT, REMOVE, etc...
When debugging, I step through each ling, but when it gets to btnRemove_Click, it steps through removing but does not remove anything...it acts as if I never sent a command to remove anything???
Help!
public partial class frmUpdate : Form
{
private Student student = new Student();
private string _scores;
public frmUpdate()
{
InitializeComponent();
}
public string GetUpdatedScores(Student s)
{
txtName.Text = s.Name;
_scores = s.Scores;
FillStudentGrades();
this.ShowDialog();
return _scores;
}
private void FillStudentGrades()
{
lstScores.Items.Clear();
string[] grades = splitGrades(_scores);
foreach (string s in grades)
{
lstScores.Items.Add(s.ToString());
}
}
private void lstScores_SelectedIndexChanged(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnAdd_Click(object sender, EventArgs e)
{
frmAddScore addScore = new frmAddScore();
_scores += " " + addScore.AddScore();
FillStudentGrades();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnRemove_Click(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (lstScores.SelectedIndex < 0)
{
MessageBox.Show("You Must Select A Grade.");
btnUpdate.Focus();
}
else
{
int i = lstScores.SelectedIndex;
string[] grades = splitGrades(_scores);
string message = "Are you sure you want to remove " + grades[i].ToString() + "?";
DialogResult button = MessageBox.Show(message, "Confirm Remove",
MessageBoxButtons.YesNo);
if (button == DialogResult.Yes)
{
int count = 0;
foreach (char c in grades[i])
{
if (char.IsDigit(c))
{
count++;
}
}
int a = _scores.IndexOf(grades[i].ToString());
_scores = _scores.Remove(a, (count + 1));
FillStudentGrades();
btnOk.Focus();
}
else
{
btnOk.Focus();
}
}
}
private void btnClearAll_Click(object sender, EventArgs e)
{
}
private void btnOk_Click(object sender, EventArgs e)
{
student.Name = txtName.Text;
student.Scores = _scores;
this.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
public string[] splitGrades(string s)
{
string[] grades = s.Split(' ');
return grades;
}
}
In C#, strings are immutable. _scores.Remove(i); doesn't change _scores. Instead it returns a new string object that you can assign to a variable, for example, back to _scores like this:
_scores = _scores.Remove(i);
you need to use RemoveAt methos - as you are trying to remove index and not the value
I'm writing a program to filter meal types into different categories using an observable collection. I'm using enums to categorise the meals, and I have three separate methods with the same code to split them into new collections when their respective buttons are clicked. The three enum types are, Vegetarian, Meat, and Fish. I have two observable collections, meals and filteredMeals. I was trying to create another method then pass down the Category as a parameter but I couldn't get it to work! Any help would be greatly appreciated.
private void btnVegetarian_Click(object sender, RoutedEventArgs e)
{
filteredMeals = new ObservableCollection<Meal>();
Meal newMeal = new Meal();
for (int i = 0; i < meals.Count; i++)
{
newMeal = meals[i];
if (newMeal.Category == MealCategory.Vegetarian)
{
filteredMeals.Add(newMeal);
}
}
lbxMeals.ItemsSource = filteredMeals;
}
private void btnMeat_Click(object sender, RoutedEventArgs e)
{
filteredMeals = new ObservableCollection<Meal>();
Meal newMeal = new Meal();
for (int i = 0; i < meals.Count; i++)
{
newMeal = meals[i];
if (newMeal.Category == MealCategory.Meat)
{
filteredMeals.Add(newMeal);
}
}
lbxMeals.ItemsSource = filteredMeals;
}
private void btnFish_Click(object sender, RoutedEventArgs e)
{
filteredMeals = new ObservableCollection<Meal>();
Meal newMeal = new Meal();
for (int i = 0; i < meals.Count; i++)
{
newMeal = meals[i];
if (newMeal.Category == MealCategory.Fish)
{
filteredMeals.Add(newMeal);
}
}
lbxMeals.ItemsSource = filteredMeals;
}
You need to create a new method taking a MealCategory parameter. Move the code to there, and pass the appropiate MealCategory for each of your button click handlers.
The code could then look like this:
private void btnVegetarian_Click(object sender, RoutedEventArgs e)
{
FilterMeals(MealCategory.Vegatarian);
}
private void btnMeat_Click(object sender, RoutedEventArgs e)
{
FilterMeals(MealCategory.Meat);
}
private void btnFish_Click(object sender, RoutedEventArgs e)
{
FilterMeals(MealCategory.Fish);
}
private void FilterMeals(MealCategory category)
{
filteredMeals = new ObservableCollection<Meal>();
Meal newMeal = new Meal();
for (int i = 0; i < meals.Count; i++)
{
newMeal = meals[i];
if (newMeal.Category == category)
{
filteredMeals.Add(newMeal);
}
}
lbxMeals.ItemsSource = filteredMeals;
}
Once you've got that working, you could try refactoring your FilterMeals method to be shorter. You can use LINQ to express the filter, and the ObservableCollection constructor has an overload taking an IEnumerable<T>, which could simplify it to:
private void FilterMeals(MealCategory category)
{
var filteredMeals = meals.Where(m => m.Category == category);
lbxMeals.ItemsSource = new ObservableCollection<Meal>(filteredMeals);
}
private void btnVegetarian_Click(object sender, RoutedEventArgs e)
{
Filer(MealCategory.Vegatarian).Invoke();
}
private void btnMeat_Click(object sender, RoutedEventArgs e)
{
Filer(MealCategory.Meat).Invoke();
}
private void btnFish_Click(object sender, RoutedEventArgs e)
{
Filer(MealCategory.Fish).Invoke();
}
public Action Filer(MealCategory mealCategory)
{
lbxMeals.ItemsSource = new ObservableCollection<Meal>(meals.Where(m=>m.Category=mealCategory))
}
Too cumbersome. You can simply do this:
private void btnMeat_Click(object sender, RoutedEventArgs e)
{
lbxMeals.ItemsSource = new ObservableCollection<Meal>(
meals.Where(m => m.Category == MealCategory.Meat));
}
and of course the same for Vegetarian and Fish.
after selecting values from another listbox I save multiple listbox value into a single column of a table using linq to entity
protected void link1_Click(object sender, EventArgs e)
{
if (lb1.SelectedItem != null)
{
lb2.Items.Add(new ListItem(lb1.SelectedItem.Text, lb1.SelectedItem.Value));
lb1.Items.RemoveAt(lb1.SelectedIndex);
}
}
protected void link2_Click(object sender, EventArgs e)
{
if (lb2.SelectedItem != null)
{
lb1.Items.Add(new ListItem(lb2.SelectedItem.Text, lb2.SelectedItem.Value));
lb2.Items.RemoveAt(lb2.SelectedIndex);
}
}
protected void Button5_Click(object sender, EventArgs e)
{
string Skill = lb2.SelectedItem.Text;
employee e1 = new employee();
e1.emp_skill = Skill;
je.employee.AddObject(e1);
je.SaveChanges();
mv.ActiveViewIndex = 4;
}
Are you looking for something like this ? I iterate throught all elements of the listbox Id = "lb2"
protected void Button5_Click(object sender, EventArgs e)
{
for(var i=0;i<lb2.Items.Count;i++)
{
var e1 = new employee() { emp_skill = lb2.Items[i].Text };
je.employee.AddObject(e1);
}
je.SaveChanges();
}
if you only want the selected items in the listbox Id= "lb2" :
protected void Button5_Click(object sender, EventArgs e)
{
ListItem item = null;
for(var i=0;i<lb2.Items.Count;i++)
{
item = lb2.Items[i];
if (item.Selected)
{
var e1 = new employee() { emp_skill = item.Text };
je.employee.AddObject(e1);
}
}
je.SaveChanges();
}