Column from selected Datagrid - c#

I have code that returns me the selected row from a datagrid.
Now i want to have the value of the 3th column.
The code I have below already gives me the selected row
private void BandGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var row_list = GetDataGridRows(BandGrid);
foreach (DataGridRow single_row in row_list)
{
if (single_row.IsSelected == true)
{
}
}
}
catch { }
}

Assuming that your DataGrid has an underlying data structure and you are not using datagridview, each row represents an object usually in a list of objects. You can just cast the selected row to the object's Type and pull the field of the cell you want. Also you don't have to loop through each one in the list. SelectedItem will have what you want.
Edited
private void BandGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Band single_row = (Band)BandGrid.SelectedItem;
string cellValue = single_row.Picture;
}
Edited End
If you have multi select feature on you may need to pull all iterating through SelectedItems. Note: don't make changes to the items in the foreach loop this will cause errors. You will need to make a copy of the data if you need to change the data.
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
listCells = new List<string>();
foreach(MyClass single_row in BandGrid.SelectedItems)
{
//do something with the object
listCells.add( single_row.Picture);
}
}
Example program. This sets the DataSource for the grid to List<MyClass> and every time the selection is changed textbox1 displays data in column c from the selected row.
public partial class MainWindow : Window
{
public class MyClass
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
public MainWindow()
{
InitializeComponent();
MyClass obj;
List<MyClass> bind = new List<MyClass>();
for (int i = 0; i < 10; i++)
{
obj = new MyClass();
obj.a = i;
obj.b = 2*i;
obj.c = 3*i;
obj.d = 4*i;
bind.Add(obj);
}
dataGrid1.ItemsSource = bind;
}
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
textBox1.Text = ((MyClass)dataGrid1.SelectedItem).c.ToString();
}
}
Here's the xaml
<Window x:Class="yo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="True" Height="200" HorizontalAlignment="Left" Margin="116,116,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="344" SelectionChanged="dataGrid1_SelectionChanged" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="87,41,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
</Grid>

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = GridView1.SelectedRow.Cells[2].Text;
}

Related

WPF - Bind combobox to List of custom class objects

I have a WPF project with a combobox that I'm trying to bind to a List of ComboboxItem objects. ComboboxItem is a class that I created for my sample project. This is partially working... I have my three items available to the combobox, but the displayed value is blank and the value of combobox.SelectedValue is null. I've seen several stackoverflow posts and other blog posts about how to do this. And as far as I can tell, I'm doing this right. But obviously I'm doing something wrong. Here is the source code for a test project...
XAML:
<Window x:Class="WpfTestApp_ComboBoxes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<ComboBox x:Name="cboMyCombo" Grid.Row="0"
SelectionChanged="cboMyCombo_SelectionChanged"></ComboBox>
</Grid>
</Window>
C# Code-behind:
public partial class MainWindow : Window
{
List<ComboboxItem> _list = new List<ComboboxItem>();
public MainWindow()
{
_list.Add(new ComboboxItem() { DisplayValue = "One", InternalValue = "1" });
_list.Add(new ComboboxItem() { DisplayValue = "Two", InternalValue = "2" });
_list.Add(new ComboboxItem() { DisplayValue = "Three", InternalValue = "3" });
InitializeComponent();
}
private void cboMyCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
ComboBox cb = sender as ComboBox;
MessageBox.Show(string.Format("Selected Item: {0}, Selected Value: {1}", cb.SelectedItem, cb.SelectedValue));
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cboMyCombo.ItemsSource = _list;
cboMyCombo.DisplayMemberPath = "DisplayValue";
cboMyCombo.SelectedValuePath = "InternalValue";
}
}
ComboboxItem Class:
public class ComboboxItem
{
public string DisplayValue;
public string InternalValue;
}
change
public class ComboboxItem
{
public string DisplayValue;
public string InternalValue;
}
to
public class ComboboxItem
{
public string DisplayValue {get;set;}
public string InternalValue {get;set;}
}

How to delete selected rows (using checkbox) in wpf datagrid

My WPF DataGrid is:
<dg:DataGrid Name="datagrid1" Grid.RowSpan="1" VerticalAlignment="Stretch" Grid.ColumnSpan="2">
<dg:DataGrid.Columns >
<dg:DataGridTemplateColumn>
<dg:DataGridTemplateColumn.Header>
<CheckBox Content=" Slect All" x:Name="headerCheckBox" />
</dg:DataGridTemplateColumn.Header>
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chkSelectAll" Margin="45 2 0 0"
IsChecked="{Binding IsChecked, ElementName=headerCheckBox,
Mode=OneWay}" />
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns>
</dg:DataGrid>
Also Dynamicaly I am populating the data to the datgrid.In xaml.cs file I written the below given code for deleting the selected row from the data grid but it throwing the error at line
DataGridRow item =(DataGridRow) datagrid1.ItemContainerGenerator.ContainerFromItem(datagrid1.Items[j]);
So Please have a look in to the below given code which I written for doing the same.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
for (int j = 0; j < datagrid1.Items.Count; j++)
{
DataGridRow item =(DataGridRow) datagrid1.ItemContainerGenerator.ContainerFromItem(datagrid1.Items[j]);
CheckBox ckb = (CheckBox)GetVisualChild<CheckBox>(item);
if (ckb.IsChecked.Value)
{
DataRowView drv = (DataRowView)datagrid1.Items[j];
//delete the row- updating to the database
}
}
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
Please let me know if am wrong.
Here is how I would do this. Implement an ObservableCollection of your class that inherits INotifyPropertyChanged. INotifyPropertyChanged will be used in case we want to update items in the collection.
First the xaml for the GridView
<DataGrid x:Name="gvMain" AutoGenerateColumns="True" HorizontalAlignment="Left"
VerticalAlignment="Top" Height="300" Width="300"></DataGrid>
Our class of items
public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string firstName { get; set; }
private string lastName { get; set; }
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
PropertyChangedEvent("FirstName");
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
PropertyChangedEvent("LastName");
}
}
private void PropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Next the WPF window
public ObservableCollection<MyClass> gridData { get; set; }
public MainWindow()
{
InitializeComponent();
gridData = new ObservableCollection<MyClass>();
gvMain.ItemsSource = gridData;
}
Test to add, change, delete items in the collection
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
gridData.Add(new MyClass() { FirstName = "John", LastName = "Smith" });
}
private void btnChange_Click(object sender, RoutedEventArgs e)
{
gridData[0].FirstName = "Meow Mix";
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
//using List to use .ForEach less code to write and looks cleaner to me
List<MyClass> remove = gridData.Where(x => x.LastName.Equals("Smith")).ToList();
remove.ForEach(x => gridData.Remove(x));
}
Any changes you want to make will be done with gridData.

SelectedItem of ContextMenu is null

I'm trying to get the SelectedItem of a ContextMenu.
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<StackPanel>
<ListBox x:Name="MyListBox" ItemsSource="{Binding MyList}" SelectedItem="{Binding MySelectedItem}">
<ListBox.ContextMenu>
<ContextMenu ItemsSource="{Binding OCContext}" PreviewMouseDown="ContextMenu_PreviewMouseDown"/>
</ListBox.ContextMenu>
</ListBox>
<Button Content="Delete Item" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
Code Behind
public partial class MainWindow : Window
{
public MainWindow()
{
OCContext = new ObservableCollection<string>();
MyList = new ObservableCollection<string>();
MyList.Add("Item 1");
MyList.Add("Item 2");
InitializeComponent();
}
public ObservableCollection<string> MyList { get; set; }
public ObservableCollection<string> OCContext { get; set; }
public string MySelectedItem { get; set; }
private void ContextMenu_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
MenuBase s = sender as MenuBase;
ItemCollection ic = s.Items;
string MyItem = "";
MyItem = (string)ic.CurrentItem;
MyList.Add(MyItem);
OCContext.Remove(MyItem);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (MySelectedItem != null)
{
OCContext.Add(MySelectedItem);
MyList.Remove(MySelectedItem);
}
}
}
You can Copy/Paste the code and the program should work.
The program is doing the following:
You can select an item in the ListBox. If you click on "Delete Item", the item will be deleted and added to the ContextMenu. If you click on the ContextMenu-Item, the item should be added again to the ListBox and removed from the ContextMenu. You should be able to do this over and over again...
So the ContextMenu is being binded to a collection. I get the Item with ic.CurrentItem.
The problem is that when I delete the item in the ListBox and add it again (by clicking on the item on the ContextMenu), ic.CurrentItem will be null.
Why?
Edit: Solution of Cyphryx is working, but now I'm trying to do the same by using MVVM/Binding:
XAML:
<ContextMenu x:Name="MyContext" ContextMenu="{Binding MyContextMenu}" ItemsSource="{Binding OCContext}"/>
ViewModel:
private ObservableCollection<string> _occontext;
public ObservableCollection<string> OCContext
{
get
{
if (_occontext == null)
_occontext = new ObservableCollection<string>();
MyContextMenu.Items.Clear();
foreach (var str in _occontext)
{
var item = new System.Windows.Controls.MenuItem();
item.Header = str;
item.Click += Content_MouseLeftButtonUp;
MyContextMenu.Items.Add(item);
}
return _occontext;
}
set
{
_occontext = value;
RaisePropertyChanged(() => OCContext);
}
}
private void Content_MouseLeftButtonUp(object sender, RoutedEventArgs e)
{
var s = sender as System.Windows.Controls.MenuItem;
if (s == null) return;
string ic = s.Header.ToString();
}
private System.Windows.Controls.ContextMenu _mycontextmenu;
public System.Windows.Controls.ContextMenu MyContextMenu
{
get
{
if (_mycontextmenu == null)
_mycontextmenu = new System.Windows.Controls.ContextMenu();
return _mycontextmenu;
}
set
{
_mycontextmenu = value;
RaisePropertyChanged(() => MyContextMenu);
}
}
Content_MouseLeftButtonUp is not being called?..
Rudi, from my knowledge, you cannot assign event handlers to individual objects in bound source. You can only use the WPF event handlers for the object it is tied to, hence, you'll have to fill the context menu manually, allowing you to add the event handlers at that time. In short, when you add
PreviewMouseDown="ContextMenu_PreviewMouseDown" to you WPF, the handler is assigned to the context menu, but when the binding adds the individual menu items, it does not add that handler to each item, leaving you event handless ;-) Below is code that will fix this:
WPF
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<StackPanel>
<ListBox x:Name="MyListBox" ItemsSource="{Binding MyList}" SelectedItem="{Binding MySelectedItem}" Height="Auto" MinHeight="20">
<ListBox.ContextMenu>
<ContextMenu Name="ContextMenu" Opened="ContextMenu_Opened" />
</ListBox.ContextMenu>
</ListBox>
<Button Content="Delete Item" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
Code Behind:
public MainWindow()
{
OCContext = new ObservableCollection<string>();
MyList = new ObservableCollection<string>();
MyList.Add("Item 1");
MyList.Add("Item 2");
InitializeComponent();
}
public ObservableCollection<string> MyList { get; set; }
public ObservableCollection<string> OCContext { get; set; }
public string MySelectedItem { get; set; }
private void ContextMenu_Opened(object sender, EventArgs e)
{
ContextMenu.Items.Clear();
foreach (var str in OCContext)
{
var item = new MenuItem();
item.Header = str;
item.Click += Content_MouseLeftButtonUp;
ContextMenu.Items.Add(item);
}
}
private void Content_MouseLeftButtonUp(object sender, EventArgs e)
{
var s = sender as MenuItem;
if (s == null) return;
var ic = s.Header.ToString();
MyList.Add(ic);
OCContext.Remove(ic);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (MySelectedItem != null)
{
OCContext.Add(MySelectedItem);
MyList.Remove(MySelectedItem);
}
}
I hope this helps.
Cyphryx

wpf treeview blues. I want to select an item

I'm trying to select a TreeViewItem. Now, I have access to the containing TreeViewItem and have told it to expand so I can select its kid. If it's already expanded all is well, if it's not then I run this code:
EventHandler selector = new EventHandler(delegate
{
if (selectedDirectoryTreeItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
TreeViewItem want = selectedDirectoryTreeItem.ItemContainerGenerator.ContainerFromItem(dirWeWantSelected) as TreeViewItem;
if (want == null)
return;
want.IsSelected = true;
// selectedDirectoryTreeItem.ItemContainerGenerator.StatusChanged -= selector;
}
});
selectedDirectoryTreeItem.ItemContainerGenerator.StatusChanged += selector;
So my question is, why wont it select? want is always null. I'm scouring the interwebs looking for another way of doing this but it would be cool if somebody could explain this to me
I've personally always found it easiest to stick a Selected property into my model object and then just bind the TreeViewItem Selected property to the Selected property of the model. Here is some code:
Model
public class Data : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Data()
{
DataItems = new List<Data>();
}
public string Name { get; set; }
private bool _selected;
public bool Selected
{
get { return _selected; }
set
{
_selected = value;
OnPropertyChanged("Selected");
}
}
public List<Data> DataItems { get; set; }
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:controls="clr-namespace:MyControls;assembly=MyControls"
Title="Window1">
<Window.Resources>
<Style x:Key="CustomTreeViewItem" TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding Path=Selected, Mode=TwoWay}" />
<Setter Property="IsExpanded" Value="True" />
</Style>
</Window.Resources>
<DockPanel Background="Transparent">
<TreeView x:Name="_tvTest" DockPanel.Dock="Left" ItemContainerStyle="{StaticResource CustomTreeViewItem}" Width="300" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Data}" ItemsSource="{Binding DataItems}">
<TextBlock Text="{Binding Name}" Padding="2" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Padding="2" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Button Content="Select Random TreeView Item" Click="Button_Click" Height="50" Width="200" />
</DockPanel>
</Window>
Code behind
public partial class Window1 : Window
{
private Random _random;
private List<Data> _dataItems;
public Window1()
{
InitializeComponent();
_dataItems = Init();
_tvTest.ItemsSource = _dataItems;
_random = new Random(5);
}
private List<Data> Init()
{
List<Data> dataItems = new List<Data>();
for (int i = 1; i <= 10; i++)
{
Data d1 = new Data();
d1.Name = "Data:" + i.ToString();
for (int j = 1; j <= 4; j++)
{
Data d2 = new Data();
d2.Name = "Data:" + i.ToString() + j.ToString();
d1.DataItems.Add(d2);
}
dataItems.Add(d1);
}
return dataItems;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int index = _random.Next(0, 9);
int subIndex = _random.Next(0, 3);
if (subIndex == 0)
_dataItems[index].Selected = true;
else
_dataItems[index].DataItems[subIndex - 1].Selected = true;
}
}
In my opinion, this is a bug in WPF, but I have run into the same issue several times. I never trust the ItemContainerGenerator's Status and instead loop on separate thread as such:
private void _selectTreeViewHelper(object directory) {
TreeViewItem want = null;
bool broke = false; //probably some sort of wait timeout instead, but works for sake of example
while (true) {
Dispatcher.Invoke(new Action(delegate {
want = selectedDirectoryTreeItem.ItemContainerGenerator.ContainerFromItem(directory) as TreeViewItem;
if (want != null && want.IsLoaded) {
want.IsSelected = true;
broke = true;
}
}));
if (broke) { break; }
Thread.Sleep(100);
}
}
Then call it:
var thread = new Thread(new ParameterizedThreadStart(_selectTreeViewHelper));
thread.Start(dirWeWantSelected);
Pain I know, but it works.
Thanks for the help, I figured it out. Well it works anyway but i'm not entirely sure why it didn't before... if anyone can tell me it would be lovely... I kinda combined elements of the two responses above and then added on a little bit to make it work. For some reason, no matter what i do I cant select the TVI (TreeViewElement) if its parent wasn't already expanded, even if the parent TVI said its contents were generated and, in fact, had contents i could iterate through. My solution was thus to wait for the contents to be generated and then itrate through them and find the one i wanted. It's really weird to me that I couldn't just grab a container given its contents. Meh. My code could stand to be refactored a little bit but here it is: (works perfectly)
public void listItemClickClick(object sender, RoutedEventArgs e)
{
try
{
UserFile fil = (UserFile)(sender as ListBoxItem).DataContext;
MessageBox.Show("to do: download stuff");
return;
}
catch (InvalidCastException)
{
}
try
{
dirWeWantSelected = (Directory)(sender as ListBoxItem).DataContext;
}
catch (InvalidCastException)
{
MessageBox.Show("this should never happen");
}
selectedDirectoryTreeItem.IsExpanded = true;
TreeViewItem want = null;
try
{
want = selectedDirectoryTreeItem.ItemContainerGenerator.ContainerFromItem(dirWeWantSelected) as TreeViewItem;
}
catch
{
MessageBox.Show("weird error");
}
if (want != null)
{
want.IsSelected = true;
}
else
{
selectedDirectoryTreeItem.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
}
}
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if (selectedDirectoryTreeItem.ItemContainerGenerator.Status
== System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
{
selectedDirectoryTreeItem.ItemContainerGenerator.StatusChanged
-= ItemContainerGenerator_StatusChanged;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
new Action(DelayedAction));
}
}
void DelayedAction()
{
selectedDirectoryTreeItem.Items.MoveCurrentToFirst();
Directory curr;
do
{
curr = (Directory)selectedDirectoryTreeItem.Items.CurrentItem;
if (curr.id == dirWeWantSelected.id)
{
curr.Selected = true;
return;
}
selectedDirectoryTreeItem.Items.MoveCurrentToNext();
}
while (selectedDirectoryTreeItem.Items.CurrentItem != null);
}

How to add/move multiselected items from one listbox to another listbox?

I have a small prototype that allows to add selected item from one listbox to another. I need to be able to select multiple item from listbox and move them to another and backward - from second listbox to first one. I am wondering if someone has good sample or can modify the code I already have. Thank you in advance.
Two listboxes and buttons XAML:
<Grid x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Margin="0,40,225,20">
<ListBox x:Name="LeftListBox" SelectionMode="Multiple"/>
</Border>
<Border Margin="0,40,20,20" BorderThickness="1" BorderBrush="#FFCECECE" HorizontalAlignment="Right" Width="169" Padding="5" >
<ListBox x:Name="RightListBox" BorderThickness="0" />
</Border>
<Button x:Name="AddButton" Height="40" Margin="0,3,198,0" VerticalAlignment="Center" Click="AddButton_Click" HorizontalAlignment="Right" Width="15" Content="▶" />
<Button x:Name="RemoveButton" Height="40" Margin="0,94,198,0" VerticalAlignment="Center" Click="RemoveButton_Click" HorizontalAlignment="Right" Width="15" Content="R" />
</Grid>
Code behind:
public partial class SelectServersUC : UserControl
{
private ArrayList myDataList = null;
string currentItemText ;
int currentItemIndex ;
public SelectServersUC()
{
this.InitializeComponent();
myDataList = LoadListBoxData();
LeftListBox.ItemsSource = myDataList;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
myDataList = LoadListBoxData();
LeftListBox.ItemsSource = myDataList;
}
private ArrayList LoadListBoxData()
{
ArrayList itemsList = new ArrayList();
itemsList.Add("Item1");
itemsList.Add("Item2");
itemsList.Add("Item3");
itemsList.Add("Item4");
itemsList.Add("Item5");
itemsList.Add("Item6");
itemsList.Add("Item7");
itemsList.Add("Item8");
itemsList.Add("Item9");
itemsList.Add("Item10");
return itemsList;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = LeftListBox.SelectedValue.ToString();
currentItemIndex = LeftListBox.SelectedIndex;
RightListBox.Items.Add(currentItemText);
if (myDataList != null)
{
myDataList.RemoveAt(currentItemIndex);
}
// Refresh data binding
ApplyDataBinding();
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = RightListBox.SelectedValue.ToString();
currentItemIndex = RightListBox.SelectedIndex;
// Add RightListBox item to the ArrayList
myDataList.Add(currentItemText);
// LeftListBox.Items.Add(RightListBox.SelectedItem);
RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem));
// Refresh data binding
ApplyDataBinding();
}
/// <summary>
/// Refreshes data binding
/// </summary>
private void ApplyDataBinding()
{
LeftListBox.ItemsSource = null;
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = myDataList;
}
just have a look at this
Move items from one listbox to another
http://www.c-sharpcorner.com/UploadFile/mahesh/WPFListBoxDataTransfer07272008130032PM/WPFListBoxDataTransfer.aspx
public partial class listtolist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
}

Categories