How to reload datagrid in wpf - 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;
}

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

use a combobox selection for linq query

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

WPF: get my object after ListView context menu right click instead of item index

I have ListView contains my object:
public ObservableCollection<MyObject> objects { get; set; }
This is my Context menu right click event:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
if (myListView.SelectedIndex == -1)
return;
int index = myListView.SelectedIndex;
}
So instead of take this index and find my object in my collection base on index number can i take the object at once ?
If I understand you correctly, you want to just fetch the object that has been selected
Have you tried using the .SelectedItem property of the list view?
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
if (myListView.SelectedIndex == -1)
return;
var obj = myListView.SelectedItem as MyObject;
}
Although I'm not sure why you can't just look up the object by its index in the collection. Both approaches would be valid, although the above approach has clearer intentions.

Deleting from a Data Grid View

I have created a windows form application. I want this application to be able to use Linq to SQL to search for a record, and then for that record to be selected from a data grid view and deleted.
The form contains a textbox to enter the parameter, a search button and a delete button and a datagrid.
I have the search part working correctly and the data grid is populated but don't know how to implement clicking on the record in the data grid and deleting it.
Update - I have solved the solution. Changes have only been made to the btn_Delete_Click event handler so I have included the updated code for his button after the main code.
namespace DeleteForm
{
public partial class Form1 : Form
{
LinqtoStudentDataContext linqStud = new LinqtoStudentDataContext();
public Form1()
{
InitializeComponent();
}
private void btnDelete_Click(object sender, EventArgs e)
{
}
private void btnSearch_Click(object sender, EventArgs e)
{
var lastName = from stud in linqStud.Students
where txtFind.Text == stud.LastName
select stud;
dataGridView1.DataSource = lastName;
}
}
}
Updated code -
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//linqStud.Students.DeleteAllOnSubmit();
linqStud.SubmitChanges();
}
}
First, set selection mode of DataGridView to FullRowSelect. Next, when assigning DataSource you should call ToList() - you can't use query as data source:
private void btnSearch_Click(object sender, EventArgs e)
{
var lastName = txtFind.Text;
var students = from stud in linqStud.Students
where stud.LastName == lastName
select stud;
dataGridView1.DataSource = students.ToList();
}
Get selected rows, and remove databound items (students) from context:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
var student = row.DataBoundItem as Student;
linqStud.Students.Remove(student);
linqStud.SaveChanges();
}
}

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.

Resources