I'm starting out in wpf.
I have a TreeView in which each item has a checkbox.
I'm trying to create an animation in which The checkboxes are checked programmatically inside a loop.
After researching the topic for some time, I came up with the following method -
private void Traverse_Click(object sender, RoutedEventArgs e)
{
ItemCollection items = tvMain.Items;
Task.Factory.StartNew( ()=>
Dispatcher.Invoke( (Action)(() =>
{
foreach (TreeViewItem item in items)
{
UIElement elemnt = getCheckbox();
if (elemnt != null)
{
CheckBox chk = (CheckBox)elemnt;
chk.IsChecked = !chk.IsChecked;
tvMain.Items.Refresh();
tvMain.UpdateLayout();
Thread.Sleep(500);
}
}
})));
And yet despite all of my attempts the the tree doesn't update inside the loop, only at the end. so the checkboxes are all checked at once.
How can I make the tree update inside the loop?
Thanks
Replace Thread.Sleep with Task.Delay to "sleep" asynchronously:
private async void Traverse_Click(object sender, RoutedEventArgs e)
{
ItemCollection items = tvMain.Items;
foreach (TreeViewItem item in items)
{
UIElement elemnt = getCheckbox();
if (elemnt != null)
{
CheckBox chk = (CheckBox)elemnt;
chk.IsChecked = !chk.IsChecked;
await Task.Delay(500);
}
}
}
I have created a windows form application in which there is a ListBox to display items. When I click on an item it gets selected as I have implemented lst_items_SelectedIndexChanged() method, and values are loaded in the controls to be update. But when I change the value from the controls to update the selected index in also called and throws Index Out of Bounds -1 Exception.
Here is my SelectedIndexChanged Code:
private void lst_items_SelectedIndexChanged(object sender, EventArgs e)
{
ShoppingItem myItem = new ShoppingItem();
if (lst_items.SelectedIndex > -1)
{
myItem = itemManager_obj.GetItem(lst_items.SelectedIndex);
txt_amount.Text = myItem.amount.ToString();
txt_description.Text = myItem.description;
cmb_units.SelectedIndex = (int)myItem.unit;
}
}
Here is my Update(change) button code:
private void btn_change_Click(object sender, EventArgs e)
{
ShoppingItem itemToChange = new ShoppingItem();
itemToChange = itemManager_obj.GetItem(lst_items.SelectedIndex);
bool success = false;
itemToChange = ReadIput(out success);
if (success)
{
success = itemManager_obj.ChangeItem(itemToChange,lst_items.SelectedIndex);
lst_items.Items.RemoveAt(lst_items.SelectedIndex);
lst_items.Items.Insert(lst_items.SelectedIndex, itemManager_obj.ToString());
UpdateGUI();
}
}
I am not sure why SelectedIndexChanged is called on update after this line of code is executed:
lst_items.Items.RemoveAt(lst_items.SelectedIndex);
Any idea how can I update without getting an exception index out of bound?
Regards
Store this in an int
lst_items.Items.RemoveAt(lst_items.SelectedIndex);
then do
lst_items.Items.Insert(your int, itemManager_obj.ToString());
You are getting this error because after you remove the selectedIndex, there is no longer an item selected because that item doesn't exist.
if (success)
{
int indexer=lst_items.SelectedIndex;
success = itemManager_obj.ChangeItem(itemToChange,lst_items.SelectedIndex);
lst_items.Items.RemoveAt(indexer);
lst_items.Items.Insert(indexer, itemManager_obj.ToString());
UpdateGUI();
}
I have a GridView control of xtraGrid suite in a form.
When I open the form for first time it is AllowEdit = false. I want that when I press on add new row link(built in by control) to make editable this only new inserted row. I read that I should use ShowingEditor event but I don't know how.
I wrote this so far but this does not editable the row:
private void gridViewNote_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
{
//this is first tryout
//if (gridViewNote.IsNewItemRow(gridViewNote.FocusedRowHandle))// == gridViewNote.GetFocusedDataRow())
//{
// gridColumnStagione.OptionsColumn.AllowEdit = true;
//}
//second tryout
GridView view = sender as GridView;
SchedeMaterialiDaTaglioDS.SMTAGL_NOTERow currentRow = gridViewNote.GetFocusedDataRow() as SchedeMaterialiDaTaglioDS.SMTAGL_NOTERow;
SchedeMaterialiDaTaglioDS.SMTAGL_NOTEDataTable changesTable = dsSchMatTaglio.SMTAGL_NOTE.GetChanges() as SchedeMaterialiDaTaglioDS.SMTAGL_NOTEDataTable;
e.Cancel = !view.IsNewItemRow(view.FocusedRowHandle) &&
!changesTable.Contains(currentRow);// set.Inserts.Contains(order);
}
I hope I understood your question. A few simple ways of doing this:
Adding a repository item to each column and handle the ShowingEditor event, using e.Cancel if this is supposed to be read only.
Popping up a window/textboxes, letting the user insert values and add the row with values already inserted via code.
assigning two different repository items to the same column using gridView.CustomRowCellEdit event. like such:
RepositoryItemTextEdit rep = new RepositoryItemTextEdit();
RepositoryItemTextEdit noRep = new RepositoryItemTextEdit();
noRep.ReadOnly = true;
private void button1_Click(object sender, EventArgs e)
{
gridView1.AddNewRow();
justAddedName = true;
gridView1.RefreshData();
}
private void gridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
{
if (e.Column == colname)
{
if (e.RowHandle == gridView1.RowCount - 1 && justAddedName)
{
e.RepositoryItem = rep;
}
else
{
e.RepositoryItem = noRep;
}
}
}
It's not complete, just a direction to explore.
Hope I helped.
I'm trying to get a rowindex of row at which I right clicked to call a contextmenu.
DatagridView's property contextmenu is set to this contextmenu.
Is it possible in some simple way?
Best regards
Yes, you need to handle the MouseDown event for your DataGridView and then use the HitTest method to return row and/or column index for the given coordinates.
For example:
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
if (hit.Type == DataGridViewHitTestType.Cell)
{
Console.WriteLine(hit.RowIndex);
}
}
}
I change the selection in the CellContextMenuStripNeeded event and then use the SelectedRows member to find it.
private void dataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
var Dgv = sender as DataGridView;
if (Dgv != null)
{
// Change the selection to reflect the right-click
Dgv.ClearSelection();
Dgv.Rows[e.RowIndex].Selected = true;
}
}
private void myToolStripMenuItem_Click(object sender, EventArgs e)
{
// Now pick up the selection as we know this is the row we right-clicked on
if (dataGridView.SelectedRows.Count > 0)
{
DoSomethingAmazing(dataGridView.SelectedRows[0]);
}
}
This also has the desired effect of highlighting a row that you r-click on.
I want to enable the user to highlight a row on the WPF DataGrid and press delete key to delete the row.
the functionality is already built into the UI of the grid, so to the user, the row disappears
I currently handle this on the SelectionChanged event (code below)
I loop through all the "e.RemovedItems" and delete them with LINQ
Problem is: even when you simply select a row and move off of it, selection change is fired and that row is in e.RemovedItems (which is odd, why would simply selecting something put it in a RemovedItems container?).
So I am looking for a DeleteKeyPressed event so I can simply handle it. What is that event called?
I am using the March 2009 toolkit.
XAML:
<Grid DockPanel.Dock="Bottom">
<toolkit:DataGrid x:Name="TheDataGrid"
SelectionChanged="TheDataGrid_SelectionChanged"
AutoGenerateColumns="True"
RowEditEnding="TheDataGrid_RowEditEnding"/>
code-behind:
private void TheDataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (e.RemovedItems.Count > 0)
{
Message.Text = "The following were removed: ";
foreach (object obj in e.RemovedItems)
{
Customer customer = obj as Customer;
Message.Text += customer.ContactName + ",";
_db.Order_Details.DeleteAllOnSubmit(
customer.Orders.SelectMany(o => o.Order_Details));
_db.Orders.DeleteAllOnSubmit(customer.Orders);
_db.Customers.DeleteOnSubmit(customer);
}
}
try
{
_db.SubmitChanges();
}
catch (Exception ex)
{
Message.Text = ex.Message;
}
}
ANSWER:
Thanks lnferis, that was exactly what I was looking for, here is my finished delete handling event for the datagrid, note the KeyDown event doesn't fire for some reason.
XAML:
<toolkit:DataGrid x:Name="TheDataGrid"
KeyDown="TheDataGrid_KeyDown"
PreviewKeyDown="TheDataGrid_PreviewKeyDown"
AutoGenerateColumns="True"
RowEditEnding="TheDataGrid_RowEditEnding"/>
code-behind
private void TheDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
var grid = (DataGrid)sender;
if (grid.SelectedItems.Count > 0)
{
string checkMessage = "The following will be removed: ";
foreach (var row in grid.SelectedItems)
{
Customer customer = row as Customer;
checkMessage += customer.ContactName + ",";
}
checkMessage = Regex.Replace(checkMessage, ",$", "");
var result = MessageBox.Show(checkMessage, "Delete", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
foreach (var row in grid.SelectedItems)
{
Customer customer = row as Customer;
_db.Order_Details.DeleteAllOnSubmit(
customer.Orders.SelectMany(o => o.Order_Details));
_db.Orders.DeleteAllOnSubmit(customer.Orders);
_db.Customers.DeleteOnSubmit(customer);
}
_db.SubmitChanges();
}
else
{
foreach (var row in grid.SelectedItems)
{
Customer customer = row as Customer;
LoadData();
_db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, customer); //TODO: this doesn't refresh the datagrid like the other instance in this code
}
}
}
}
}
private void TheDataGrid_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("never gets here for some reason");
}
The RemovedItems items reflects the items removed from the selection, and not from the grid.
Handle the PreviewKeyDown event, and use the SelectedItems property to delete the selected rows there:
private void PreviewKeyDownHandler(object sender, KeyEventArgs e) {
var grid = (DataGrid)sender;
if ( Key.Delete == e.Key ) {
foreach (var row in grid.SelectedItems) {
... // perform linq stuff to delete here
}
}
}
XAML
<DataGrid ItemsSource="{Binding}" CommandManager.PreviewCanExecute="Grid_PreviewCanExecute" />
Code behind
private void Grid_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
DataGrid grid = (DataGrid)sender;
if (e.Command == DataGrid.DeleteCommand)
{
if (MessageBox.Show(String.Format("Would you like to delete {0}", (grid.SelectedItem as Person).FirstName), "Confirm Delete", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
e.Handled = true;
}
}
What are you binding your DataGrid to?
Ideally, you should react to CollectionChanged events on the collection you are binding to. That way, your logic (deletion of removed items) will be separated from your UI.
You can build an Observable collection containing your objects and bind it to ItemsSource just for that purpose if the original collection does not have the necessary events.
It might not suit your specific setup, but that's how I usually do it.
Please follow the below code. I have succeeded with the below code.
Please let me know if changes are required.
private void grdEmployee_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Device.Target.GetType().Name == "DataGridCell")
{
if (e.Key == Key.Delete)
{
MessageBoxResult res = MessageBox.Show("Are you sure want to delete?", "Confirmation!", MessageBoxButton.YesNo,MessageBoxImage.Question);
e.Handled = (res == MessageBoxResult.No);
}
}
}
A little late to the party, but to get Inferis answer working:
Dim isEditing = False
AddHandler dg.BeginningEdit, Sub() isEditing = True
AddHandler dg.RowEditEnding, Sub() isEditing = False
AddHandler dg.PreviewKeyDown, Sub(obj, ev)
If e.Key = Key.Delete AndAlso Not isEditing Then ...
This fixes epalms comment: "if you're editing a cell and use the delete key to remove some characters in the cell, you'll end up deleting the whole row"
The cleanest solution is to use PreviewCanExecute like answered by flux, this is a completed solution to make it a bit more clear for anybody that overlooked his answer like I did:
private void Grid_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Command == DataGrid.DeleteCommand)
{
if (MessageBox.Show($"Delete something from something else?", "Confirm removal of something", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
// Do what ever needs to be done when someone deletes the row
}
else
{
e.Handled = true;
// Handled means.. no worries, I took care of it.. and it will not delete the row
}
}
}
No need to hook on to CommandManager.Executed after this.
You want to handle the KeyUp or KeyDown event and check the pressed Key for Delete.
private void OnKeyDown(object sender, KeyEventArgs e) {
if ( Key.Delete == e.Key ) {
// Delete pressed
}
}