How can I save multiple Listbox value - c#

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

Related

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

Drag and Drop on List Boxes of Objects

I have a List of Employee. I just want to perform simple Drag and Drop. i.e. drag and remove an Employee from SourceListBox and Add that Employee Object in TargetListBox.
I am having two problems.
Removing the employee from SourceListBox gives me an exception and the value displayed in TargetListBox is not the Employee Object but the string Drag_and_Drop.Employee
private List<Employee> emp = new List<Employee>();
emp.Add(new Employee { EmployeeId = 1, Name = "Arslan" });
emp.Add(new Employee { EmployeeId = 2, Name = "Talha" });
SourceListBox.ItemsSource = emp;
SourceListBox.DisplayMemberPath = "Name";
SourceListBox.SelectedValuePath = "EmployeeId";
private void SourceListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DragDropEffects dde = DragDrop.DoDragDrop(SourceListBox, SourceListBox.SelectedItem, DragDropEffects.All);
var empi = (Employee) SourceListBox.SelectedItem;
if(dde == DragDropEffects.All)
{
emp.Remove(empi);
SourceListBox.ItemsSource = null;
SourceListBox.ItemsSource = emp;
}
}
private void TargetListBox_DragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.All;
TargetListBox.Items.Add(e.Data.GetData(typeof(Employee)));
}
Basic example from C# Drag and Drop From listBox
public object lb_item = null;
private void listBox1_DragLeave(object sender, EventArgs e)
{
ListBox lb = sender as ListBox;
lb_item = lb.SelectedItem;
lb.Items.Remove(lb.SelectedItem);
}
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
if (lb_item != null)
{
listBox1.Items.Add(lb_item);
lb_item = null;
}
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
lb_item = null;
if (listBox1.Items.Count == 0)
{
return;
}
int index = listBox1.IndexFromPoint(e.X, e.Y);
string s = listBox1.Items[index].ToString();
DragDropEffects dde1 = DoDragDrop(s, DragDropEffects.All);
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
lb_item = null;
}
and for to expand knowledge http://www.codeproject.com/Articles/5883/Two-ListBoxes-Drag-and-Drop-Example

Trying to shorten my program so code isn't repeated

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.

populate DropDownList with a list

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

C# How do I use a value from one function in another?

How can I use a value from the reading function in the button1_Click function?
public void reading(object sender, EventArgs e)
{
DialogResult reading_from_folder = new DialogResult();
reading_from_folder = folderBrowserDialog1.ShowDialog();
if (reading_from_folder == DialogResult.OK)
{
string[] files_in_folder = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
...
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (string file in files_in_folder) // How do I access files_in_folder?
{
ListViewItem li = new ListViewItem(file);
}
}
You need to store it somehow, for example as a private member:
string some_value = null;
public void reading(object sender, EventArgs e)
{
some_value = "Foobar";
}
private void button1_Click(object sender, EventArgs e)
{
if (some_value != null)
{
// ...
}
}
// Make it a member variable
private string[] mFilesInFolder = null;
public void reading(object sender, EventArgs e)
{
DialogResult reading_from_folder = new DialogResult();
reading_from_folder = folderBrowserDialog1.ShowDialog();
if (reading_from_folder == DialogResult.OK)
{
mFilesInFolder = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
}
}
private void button1_Click(object sender, EventArgs e)
{
DoFileInFolderOperation();
}
private void DoFilesInFolderOperation()
{
if(mFilesInFolder != null)
{
foreach (string file in mFilesInFolder)
{
ListViewItem li = new ListViewItem(file);
}
}
}

Categories

Resources