use a combobox selection for linq query - wpf

I have a combobox that gets populated from a database table. When the combobox is diplayed in the window it has the StationName, but it also has a "hidden" value for a StationId. Here is how I get the combobox to display the choices:
StationBox.ItemsSource = dc.WasteTrackerStations;
How can I get to that StationId property to use that in a seperate query to populate a datagrid? This is the code for my SelectionChanged event:
private void StationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var miquery = from mi in dc.WasteTrackerDBs
where mi.StationId == [this value needs to be StationId from combobox selection]
select new
{
mi.MenuItem,
mi.LeftOver,
mi.Par,
mi.UoM,
mi.StationId
};
EWDataGrid.ItemsSource = miquery;
}

ComboBox has SelectedItem property. It will be an element of dc.WasteTrackerStations collection (or null). Cast it to concrete type and all properties will be accessible:
private void StationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = StationBox.SelectedItem as WasteTrackerStation;
if (item == null) return;
var selectedStationId = item.StationId;
var miquery = from mi in dc.WasteTrackerDBs
where mi.StationId == selectedStationId
select new
{
mi.MenuItem,
mi.LeftOver,
mi.Par,
mi.UoM,
mi.StationId
};
EWDataGrid.ItemsSource = miquery;
}

Related

How to update item in ListBox in WindowsForm Application in C#

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

How to reload datagrid in wpf

I have a WPF application where I want to select item from datagrid and pass to textbox. after that on add button selected gridrow must be remove. I have a stored procedure to remove from table. And at same time reload the table in same datagrid.
I tried this code
private void refresh()
{
datagrid1.items.refresh();
}
private void btnAdd_Click(object Sender, RoutedEventArg e)
{
refresh();
}
private void datagrid1_SelectionChange(object Sender, RoutedEventArg e)
{
var selectedrow = datagrid1.selectedItem as datarowview;
var id = selectedrow["Tagid"]; // Here I get error that object reference is not set is an instance of an object
string s = conver.tostring(id);
txttextbox1.text= s;
}
After click add button, I get the error
Object reference not set to an instance of an object
You are forcing your selected item as datarowView which it is not, cast to correct type
var selectedrow = datagrid1.selectedItem as DataRowView
SelectedItem is type of object that is bound to grid not row
Try doing this
private void datagrid1_SelectionChange(object Sender, RoutedEventArg e)
{
var selectedItem = datagrid1.selectedItem as MY_Custom_Object;
var id = selectedItem.Tagid;
string s = Convert.ToString(id);
txttextbox1.text= s;
}

How to enable editing for new inserted row in a GridView while gridview is allowedit = false?

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.

How to sort the [include] entitycollection in Ria Silverlight

I have datagrid with another datagrid in the rowdetails and I am not able to sort the details view
I have tried the following but no success :(
The main datagrid is populated in the following manner:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
NamskeidinDomConTxt = new Namskeidin_DomainContext();
this.NamskeidinDomConTxt.Load(this.NamskeidinDomConTxt.GetNamskeidQuery(), LoadBehavior.RefreshCurrent, loadOperation =>
{
PagedCollectionView pcView = new PagedCollectionView(loadOperation.Entities);
pcView.SortDescriptions.Add(new SortDescription("Heiti", ListSortDirection.Ascending));
namskeidDataGrid.ItemsSource = pcView;
}, null);
}
The datagrid in the detailsrow of the main datagrid is populated in the following manner:
First I catch the following event and get the details datagrid.
private void namskeidsHlutarDataGrid_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
{
verkefniDataGrid = (e.DetailsElement as FrameworkElement).FindName("VerkefniDataGrid") as DataGrid;
Verkefni_DomConTxt = new Verkefni_DomainContext();
}
and then the this event fiers so I can fill the details datagrid when I have got the id:
private void namskeidsHlutarDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
var item = dataGrid.SelectedItem;
if (item != null)
{
nHlutaId = ((Entity)item).GetIdentity().ToString();
Verkefni_DomConTxt.Load(Verkefni_DomConTxt.GetVerkefniQuery().Where(v => v.NamskeidsHluta_ID == nHlutaId),
LoadBehavior.RefreshCurrent, loadOperation =>
{
verkefniDataGrid.ItemsSource = loadOperation.Entities;
}, null);
}
}
private void GridName_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
{
var dataGrid = (e.DetailsElement as FrameworkElement).FindName("detailsDataGrid") as DataGrid;
PagedCollectionView pcView = new PagedCollectionView(dataGrid.ItemsSource as IEnumerable);
pcView.GroupDescriptions.Clear();
pcView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
pcView.Refresh();
}
There are actualy three datagrids details/details
Can anyone help me with this?
You're creating a new PagedCollectionView but your DataGrid's ItemsSource is still bound to the plain IEnumerable. You'll need to bind the ItemsSource to your PagedCollectionView.
Updated: So based on your updated code you should just load the child grid the same way you load the parent grid. So instead of:
Verkefni_DomConTxt.Load(Verkefni_DomConTxt.GetVerkefniQuery().Where(v => v.NamskeidsHluta_ID == nHlutaId), LoadBehavior.RefreshCurrent,
loadOperation => { verkefniDataGrid.ItemsSource = loadOperation.Entities;}, null);
You could just create your data view here and set the items source to point to it:
Verkefni_DomConTxt.Load(Verkefni_DomConTxt.GetVerkefniQuery().Where(v => v.NamskeidsHluta_ID == nHlutaId), LoadBehavior.RefreshCurrent,
loadOperation => {
PagedCollectionView pcView = new PagedCollectionView(loadOperation.Entities);
pcView.GroupDescriptions.Clear();
pcView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
verkefniDataGrid.ItemsSource = pcView;
}, null);
And then get rid of your other event that tries to create the view.

Get RowIndex via ContextMenu?

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.

Resources