Trying to shorten my program so code isn't repeated - c#

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.

Related

C# Get deleted items and changed items to list

I have a question to get all deleted items to a new list and also for the changed items. I'm using a datagridview with a sortable bindingsource. For all new items it's already working(last part of the code)
Thanks!
namespace Levelapp
{
public partial class LevelView : Form
{
FilterLevel m_filterLevel;
int m_filterLevelTotal;
public LevelView()
{
InitializeComponent();
}
public LevelView(FilterLevel opt)
{
InitializeComponent();
m_filterLevel = opt;
bindingSource1.DataSource = typeof(LevelResource);
dataGridView1.DataSource = bindingSource1;
bindingSource1.DataSource = m_filterLevel.FoundLevels;
m_filterLevelTotal = bindingSource1.Count;
}
private void newSheet_Click(object sender, EventArgs e)
{
string newItemName = "Sheet" + " " + "1";
string newItemNumber = "A-00";
LevelResource newItem = new LevelResource();
newItem.Name = newItemName;
newItem.Number = newItemNumber;
bindingSource1.Add(newItem);
}
private void deleteSheet_Click(object sender, EventArgs e)
{
bindingSource1.RemoveCurrent();
}
private void ok_Click(object sender, EventArgs e)
{
for (int i = m_filterLevelTotal; i < bindingSource1.Count; i++)
{
bindingSource1.Position = i;
LevelResource newSheet = bindingSource1.Current as LevelResource;
}
}
}
}
Thanks for the quick response. But i get an Error at the bool result line. This code will be used in Revit. Below the part how i put your code under the deleteSheet button
private void deleteSheet_Click(object sender, EventArgs e)
{
for (int i = 0; i < bindingSource1.Count; i++)
{
bindingSource1.Position = i;
var view = bindingSource1.Current as DataRowView;
bool result = view.Row.RowState == DataRowState.Added || view.Row.RowState == DataRowState.Unchanged;
if (result)
{
// new or didn't modified, work as normal
}
else
{
// add to another list
}
}
}

ArgumentOutOfRangeException on an object listview when hitting tab

I have an object list view that has two text columns. When I edit the left column and hit tab to go to the right I receive a "ArgumentOutOfRangeException" with an index of -1. Looks like the index is something internal to the list view because I debugged my application and found no errors. Here is the code :
public partial class SummaryOverviewSettingsDlg : Form
{
private List<SummaryDataset> _localSummaryDatasets = new List<SummaryDataset>();
private bool _includeLimits;
private SummaryOverviewSettings _summaryOverviewSettings;
public bool IncludeLimits { get { return _includeLimits; } }
public SummaryOverviewSettingsDlg(SummaryOverviewSettings summaryOverviewSettings)
{
InitializeComponent();
if (summaryOverviewSettings.Datasets != null)
{
_localSummaryDatasets.AddRange(summaryOverviewSettings.Datasets);
}
_summaryOverviewSettings = summaryOverviewSettings;
}
private void DataFilesListDlg_Load(object sender, EventArgs e)
{
foreach(var dataFile in _localSummaryDatasets)
{
olvFilePaths.AddObject(dataFile);
}
LimitsCheckbox.Checked = _summaryOverviewSettings.ShowLimits;
}
private void OlvFilePaths_CellRightClick(object sender, CellRightClickEventArgs e)
{
var contextMenuSymbol = new ContextMenuStrip();
ToolStripItem item;
item = contextMenuSymbol.Items.Add("Add sample");
item.Click += ContextMenuAddFilePath;
if (e.Model != null)
{
contextMenuSymbol.Items.Add("-");
item = contextMenuSymbol.Items.Add("Delete sample");
item.Click += ContextMenuDeleteFilePath;
}
olvFilePaths.ContextMenuStrip = contextMenuSymbol;
}
private void ContextMenuAddFilePath(object sender, EventArgs e)
{
var item = new SummaryDataset()
{
SampleName = "Sample",
Path = "Path"
};
_localSummaryDatasets.Add(item);
// Rebuild the list in the GUI
olvFilePaths.ClearObjects();
foreach (var dataFile in _localSummaryDatasets)
{
olvFilePaths.AddObject(dataFile);
}
olvFilePaths.AutoResizeColumns();
}
private void ContextMenuDeleteFilePath(object sender, EventArgs e)
{
if (olvFilePaths.SelectedObject != null)
{
var item = (SummaryDataset)olvFilePaths.SelectedObject;
olvFilePaths.RemoveObject(item);
_localSummaryDatasets.Remove(item);
}
}
private void OlvFilePaths_CellEditFinished(object sender, CellEditEventArgs e)
{
if (e.Control is TextBox textBox)
{
var oldValue = (string)e.Value;
var newValue = (string)e.NewValue;
var col = e.Column.AspectName;
var index = e.ListViewItem.Index;
if (newValue != oldValue)
{
if (col == "SampleName")
{
_localSummaryDatasets[index].SampleName = newValue;
}
else
{
_localSummaryDatasets[index].Path = newValue;
}
}
}
// Rebuild the list in the GUI
olvFilePaths.ClearObjects();
foreach (var dataFile in _localSummaryDatasets)
{
olvFilePaths.AddObject(dataFile);
}
olvFilePaths.AutoResizeColumns();
}
private void OkButton_Click(object sender, EventArgs e)
{
_summaryOverviewSettings.Datasets.Clear();
_summaryOverviewSettings.Datasets.AddRange(_localSummaryDatasets);
_summaryOverviewSettings.ShowLimits = _includeLimits;
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void LimitsCheckbox_CheckedChanged(object sender, EventArgs e)
{
_includeLimits = LimitsCheckbox.Checked;
}
}

Running Total of Ones Count in WinForms

I'm writing a code where we need to find all the ones in a character and display them as a total. However, the code updates the total for each character pressed, rather than adding all previous ones counts.
Help would be appreciated.
namespace ica5_eventdriven
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
listBox1.Enabled = true;
lblKeyCode.Text = e.KeyChar.ToString();
listBox1.Items.Add(Convert.ToString(Convert.ToByte(e.KeyChar), 2));
List<byte> byteList = new List<byte>();
byteList.Add((byte)e.KeyChar);
byte binaryVal = Convert.ToByte(e.KeyChar);
int ones = 0;
int zeros = 0;
foreach (byte val in byteList)
{
for (int i = 0; i < 8; i++)
{
if ((binaryVal & 1) == 1)
{
ones++;
lblOnesCount.Text = ones.ToString();
}
else
zeros++;
binaryVal >>= 1;
}
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Having problems removing a string from a sting list

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

How can I save multiple Listbox value

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

Categories

Resources