Updating a Databound GridView with changes - c#

I have a DataGridView on a form that is databound to a list of objects. I have several column including a checkbox column. The requirement is that only one item in the collection may have the databound boolean property set to true at a given time. The data object is named Interval, the Property in question is Program:
public bool Program
{
get { return _program; }
set
{
if (value)
{
Parent.Intervals.Except(new[] { this }).ForEach(interval => interval.Program = false);
}
_program = value;
OnPropertyChanged();
}
}
My expected behavior would be that clicking the databound checkbox would set the Program property for one instance of Interval to true, and in so doing, would set the Program property on all other instances to false. That is indeed what happens, however the datagridview does not update correctly. It will leave previous checkboxes checked and after tabbing off the cell or mousing over another checkbox, then it will update that particular checkbox.
How can I get the datagrid view to accurately show the state of my objects. I trusted you, DataGridView! You lied to me. I... I can never trust anything you say again.

The solution is to use a BindingList instead. When binding to a regular List or other collection (that is not of a Binding specific bent), only the selected rows values are updated. BindingList, however, has the added benefit that properties from all of the items are updated, not just the selected Row. Keep in mind that if you are using something like AddRange (from List) you may have to modify your code to add items either at initialization time or via a loop, as BindingList does not have an AddRange method (although an extension method could be written).

Try this
private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((bool)dg.Rows[e.RowIndex].Cells[CheckBoxColumnIndex].Value)
{
var rows = (from DataGridViewRow row in Clients.Rows
where row.Index != e.RowIndex
select row).ToArray();
foreach(DataGridViewRow row in rows)
{
row.Cells[CheckBoxColumnIndex].Value = false;
}
}
}

Related

How Can i Convert datagridview datasource to BindingListView (Equin.ApplicationFramework.BindingListView)

I set this DataBindingComplete event to my datagridview. I want every datasource that binding to datagridview can be sortable by clicking on column.
void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView dataGridView = sender as DataGridView;
foreach (DataGridViewColumn column in dataGridView.Columns)
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
all of my datasource is List and bindingsource doesnot sort when my list is ended by .ToList
Now . how can i convert datagridview.datasource to Equin.ApplicationFramework.BindingListView and set it again to datasource for make any datagridview sortable?
Proper usage of Equin.ApplicationFramework.BindingListView would be as follows
Upon creation of your form:
Create a BindingListView. It will be filled later with the items that you want to display / sort / filter
Create a BindingSource.
Create a DataGridView.
Add the columns to the properties you want to show
The latter three steps can be done in visual studio designer. If you do that, The code will be in InitializeComponents.
Suppose you want to show / sort / filter elements of MyType Your form will be like:
public class MyForm : Form
{
private BindingListView<MyType> MyItems {get; set;}
public MyForm()
{
InitializeComponent();
this.MyItems = new BindingListView<MyType>(this.components);
// components is created in InitializeComponents
this.MyBindingSource.DataSource = this.MyItems;
this.MyDataGridView.DataSource = this.MyBindingSource;
// assigning the DataPropertyNames of the columns can be done in the designer,
// however doing it the following way helps you to detect errors at compile time
// instead of at run time
this.columnPropertyA = nameof(MyType.PropertyA);
this.columnPropertyB = nameof(MyType.PropertyB);
...
}
You can do without the BindingSource, you can assign the BindingListViewdirectly to the DataSource of the DataGridView. Sorting and Filtering will still work. However the BindingSource will help you to access the currently selected item.
private MyType SelectedItem
{
get {return ((ObjectView<MyType>)this.MyBindingSource.Current)?.Object; }
}
private void DisplayItems (IEnumerable<MyType> itemsToDisplay)
{
this.MyItems.DataSource = itemsToDisplay.ToList();
this.MyItems.Refresh(); // this will update the DataGridView
}
private IEnumerable<MyType> DisplayedItems
{
get {return this.MyItems; }
// BindingListview<T> implements IEnumerable<T>
}
This is all. You don't need to create special functions to sort on mouse clicks. The sorting will be done automatically inclusive deciding on the sort order and displaying the correct sorting glyphs. If you want to sort programmatically:
// sort columnPropertyA in descending order:
this.MyDataGridView.Sort(this.columnPropertyA.ListsortDirection.Descending);
One of the nice things about the BindingListView is the filtering option:
// show only items where PropertyA not null:
this.MyItems.ApplyFilter(myItem => myItem.PropertyA != null);
// remove the filter:
this.MyItems.RemoveFilter();
(I'm not sure if a Refresh() is needed after applying or removing a filter

Alternative to DataGridView DataBindingComplete Event

As stated here the DataBindingComplete event for a DataGridView is fired whenever the contents of the data source change, or a property such as DataSource changes. This results in the method being called multiple times.
I am currently using the DataBindingComplete event to do some visual formatting to my form. For example, I make the text in the first column (column 0) appear as Row Headers and then hide that column (see code below).
private void grdComponents_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in grdComponents.Rows)
{
row.HeaderCell.Value = row.Cells[0].Value.ToString();
}
grdComponents.Columns[0].Visible = false;
// do more stuff...
}
It is unnecessary to execute this code more than once, and I am looking to put it into a place where that can happen. Unfortunately it didn't work when I added the snippet to the end of my form's Load method (after I set the DataSource of my DataGridView), nor did it work in the DataSourceChanged event.
Yes, you can use DataSourceChanged event, but be aware, that it occurs only when data source is changed. Additionally, DataBindingComplete offers you information why it has happend - through e.ListChangedType:
Reset = 0,// Much of the list has changed. Any listening controls should refresh all their data from the list.
ItemAdded = 1,// An item added to the list
ItemDeleted = 2,// An item deleted from the list.
ItemMoved = 3,// An item moved within the list.
ItemChanged = 4,// An item changed in the list.
PropertyDescriptorAdded = 5,// A System.ComponentModel.PropertyDescriptor was added, which changed the schema.
PropertyDescriptorDeleted = 6,// A System.ComponentModel.PropertyDescriptor was deleted, which changed the schema.
PropertyDescriptorChanged = 7// A System.ComponentModel.PropertyDescriptor was changed, which changed the schema.
According to this answer:
https://social.msdn.microsoft.com/forums/windows/en-us/50c4f46d-c3b8-4da7-b08f-a751dca12afd/databindingcomplete-event-is-been-called-twice
the whole thing happens because you don't have DataMember property set in your dataGridView. And you can set it only if you want to set particular table from database which is set as your DataSource of dataGridView. Other way - throws an exception.
The simplest way will be just to execute this code once:
Add a flag like Boolean isDataGridFormatted in your form.
And check it like
private void grdComponents_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (this.isDataGridFormatted )
return;
foreach (DataGridViewRow row in grdComponents.Rows)
{
row.HeaderCell.Value = row.Cells[0].Value.ToString();
}
grdComponents.Columns[0].Visible = false;
// do more stuff...
this.isDataGridFormatted = false;
}
A bit better will be to prepare your DataGridView during the form construction. As I understand your columns won't change during the course of your program but you don't want to initialize everything manually. You could load some dummy one-item(one-row) data during the initialization:
private void Initialize_DataGridView()
{
// Add dummy data to generate the columns
this.dataGridView_Items.DataContext = new Item[]{ new Item {Id = 5, Value = 6}};
// Make your formatting
foreach (DataGridViewRow row in grdComponents.Rows)
{
row.HeaderCell.Value = row.Cells[0].Value.ToString();
}
grdComponents.Columns[0].Visible = false;
// Reset the dummy data
this.dataGridView_Items.DataContext = null; // Or new Item[]{};
}
...
public MyForm()
{
Initialize();
this.Initialize_DataGridView();
}
I am not sure that exactly such code will work with dataGridView but it is close enough.
Of course an event would have been a nearly ideal solution but there's hardly any that deals with successful autogeneration of columns http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview_events(v=vs.110).aspx except the AutoGenerateColumnChanged but that is not what we need.
While it is possible to use the ColumnAdded - it will probably execute only once foreach of the autogenerated column, the actual implementation could become an overkill and will be even less direct than already mentioned approaches.
If you will have some time and desire you could create your own DataGridView derived class, take Boolean isDataGridFormatted from your form and implement all the initialization(or event hooking) inside the custom DataGridView.

DataGridView selecting a specific row and retrieving all column values to an object array

I want to perform operation that On a button click event , Grid Currentrow entire data is passed to an object array
I have tried to search through following links :
DataGridView selecting a specific row and retrieving its values
Getting data from selected datagridview row and which event?
But they are talking about particular cell value
i tried to perform with code
DataRowView currentDataRowView = (DataRowView)grdGLSearch.CurrentRow.DataBoundItem;
DataRow row1 = currentDataRowView.Row;
But currentDataRowView is retrieving null
one of My Senior succesfully created a generic property GetSelectedRow()
it works like this :
var object =grdGLSearch.GetSelectedRow<T>();
and it has definition
public T GetSelectedRow<T>()
{
if (this.CurrentRowIndex == -1)
{
return default(T);
}
return (base.DataSource as BindingList<T>)[this.CurrentRowIndex];
}
But it is binded to only one Main grid , i also want to use this property to another Grids
I dont want data of a particular column , i want entire row data .. and dont want any iteration to be perform ...
Is there any single liner operation for this ?
Please suggest if I am missing any links
Since you are only showing 2 lines of code, I am really not sure exactly what is going on. First off, I get you want the entire row when you click some button. However, you never state how the current row is being selected.
In order to get the full selected row, you must have a selected cell. The MSDN documentation says this on the page for DataGridView.SelectedRow. So I am assuming that the user will click a cell, and you want the entire row. I would create a variable that will hold your selected row. Then when the user clicks the cell, automatically select the row and save it. Then when the button is clicked, just retrieve the the already saved row.
private DataGridViewRow selectedRow { get; set; }
Then have the event for when the user clicks a cell
private void grdGLSearch_CellClick(object sender, DataGridViewCellEventArgs e)
{
selectedRow = grdGLSearch.Rows[e.RowIndex];
}
Finally, the button click event
private void SubmitBtn_ItemClick(object sender, ItemClickEventArgs e)
{
// to target the specific data
var cellVal1 = selectedRow.Cells["SpecificCell1"].Value;
var cellVal2 = selectedRow.Cells["SpecificCell2"].Value;
}

how to prevent autoselection of first item in GridView on databind?

When I databind my GridView to an ObservableCollection, the first item of the collection is automatically selected. The SelectionMode property of the GridView is set to multiple. Is there some way to prevent this auto-selection? Or on what event should I listen so that I can reset the SelectedIndex of the GridView back to -1?
Set the IsSynchronizedWithCurrenItem property to false on the gridview in xaml
There is acutally a pretty simple solution. I set the SelectionMode of the GridView to None in the XAML. Then, when the page is created, I change the SelectionMode to Multiple.
publicPage()
{
this.InitializeComponent();
itemListView.SelectionMode = ListViewSelectionMode.Multiple;
}
However, the problem I am having seems to be caused by my own program. This is a workaround for the issue I am having, the autoselection is not the default behavior.
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/da7e9f3b-9a3e-47ca-8223-b50539293f5f
My situation is the opposite. I have a GridView that was bind to an ObservableCollection, and I wanted the 1st item to be selected but it was not! I figured out why that was the case though. There are 2 ways to generate my ObservableCollection and depending on which method I chose, the 1st item is either selected or not.
for example, I have a variable ItemList in my viewmodel which I bind to my GridView
public ObservableCollection<Item> ItemList { get; private set; }
Method 1 (nothing selected)
public void getData()
{
var myList = // get your list here
for (int i = 0; i < myList.Count; i++)
{
this.ItemList.add(myList[i]);
}
}
Method 2 (1st item automatically selected)
public void getData()
{
var myList = // get your list here
this.ItemList = myList
}

DataGridView throwing "InvalidOperationException: Operation is not valid..." when adding a row

I want an OpenFileDialog to come up when a user clicks on a cell, then display the result in the cell.
It all works, except that the DataGridView displays an extra row, for adding values to the list it's bound to. The row shows up if dataGridView.AllowUserToAddNewRows == true, which is what I want. What I don't want is for the application to crash when that row is edited programatically; instead, it should do exactly what it would do if the user had edited that row manually (add the new row to the underlying list, push another empty row onto the grid for adding values).
I read about SendKeys.Send(), which should make the DataGridView behave exactly as though the user had typed the value in; however, it does not work either. Here is what I am trying:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
dataGridView1.CurrentCell = cell;
//simply doing a cell.Value = etc. will cause the program to crash
cell.ReadOnly = false;
dataGridView1.Columns[cell.ColumnIndex].ReadOnly = false;
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
dataGridView1.BeginEdit(true);
SendKeys.Send(openFileDialog1.FileName + "{Enter}");
dataGridView1.EndEdit();
cell.ReadOnly = true;
dataGridView1.Columns[cell.ColumnIndex].ReadOnly = true;
}
//I would expect the FileName would be in the cell now, and a new empty
//row tacked onto the end of the DataGridView, but it's not; the DataGridView
//is not changed at all.
I found a workaround on this page, though I don't know why it works
public MyForm()
{
InitializeComponent();
//Create a BindingSource, set its DataSource to my list,
//set the DataGrid's DataSource to the BindindingSource...
_bindingSource.AddingNew += OnAddingNewToBindingSource;
}
private void OnAddingNewToBindingSource(object sender, AddingNewEventArgs e)
{
if(dataGridView1.Rows.Count == _bindingSource.Count)
{
_bindingSource.RemoveAt(_bindingSource.Count - 1);
}
}
I'm getting very sick of spending so much time dealing with Visual Studio bugs...
I was having the same problem when trying to programattically edit cells with a binding source.
""Operation is not valid due to the current state of the object"
Which operation? What State? So helpful.
My code seem to work fine except when editing the last row in the grid.
Turns out the key is DataGridView.NotifiyCurrentCelldirty(true)
The correct sequence for programatically editing a cell, so it works the same as if the user did it.
(A new empty row appears when changing a cell in the last row) is something like this:
1) Make the cell to edit the current cell (do what ever you need to the current currentcell, first
like calling endEdit if it is in edit mode.)
2) Call DataGridview.BeginEdit(false)
3) Call DataGridView.NotifyCurrentCellDirty(true)
4) Modify the value.
5) Call DataGridView.EndEdit()
And you'll want to do something for the RowValidating and RowValidated events.
One of my routines for updating a cell value looks like this:
This is from a method in my class derived from DataGridView.
You could do the same thing from the containing form, calling
through a DataGridView instance, because the methods are public.
Here the calls are using an impliciit 'this.'
private void EnterTime()
{
if (CurrentRow == null) return;
SaveCurrentCell(); // Calls EndEdit() if CurrentCell.IsInEditMode
DataGridViewCell previous = CurrentCell;
CurrentCell = CurrentRow.Cells[CatchForm.TimeColumn];
BeginEdit(false);
NotifyCurrentCellDirty(true);
CurrentCell.Value = DateTime.Now;
EndEdit();
CurrentCell = previous;
}
I’m not sure why a separate call is needed.
Why doesn’t BeginEdit, or actually modifying the cell value, cause the right
things to happen?
And if you move the NotifyCurrentCellDirty call to after you actually modify the cell,
it doesn’t behave correctly either. All very annoying.
This is old, but I am running VS2010 and just come across this issue. I have a DataGridView bound to a List<T> using a BindingList<T>. I have a drag n' drop event on my DataGridView and it would throw this exception after deleting all rows from the DGV (except for the last blank one which one cannot delete) and then adding new rows to the DGV in the DragDrop handler via the BindingList<T>. This exception was not thrown if I simply added rows manually editing individual cells.
One solution I read said to handle the BindingList<T>.AddNew event, but I found that this event did not fire when calling BindingList<T>.Add() within the DragDrop event handler (I'm not sure why). I solved the issue by adding
if(bindingList.Count == 0)
bindingList.RemoveAt(0)
inside of the DragDrop event handler before adding new objects to bindingList. It seemed that adding an object to the bindingList failed when the only "object" in the bindingList was the one associated to the final blank row. The point of a BindingList<T> is to allow the developer to work with it instead of the DGV directly, but it seems doing so can cause problems in border cases.
The relationship between DGV rows and BindingList<T> rows seems to be a bit of a gray area. I have not spent much time investigating this, but it is not clear to me what is the state of the "object" in the BindingList<T> associated to the final (empty) row of the DGV. However, it does seem like the "object" at the end is only instantiated "correctly" when you interact with the final row directly (not via a DataSource).
Try this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
int row = e.RowIndex;
int clmn = e.ColumnIndex;
if(e.RowIndex == dataGridView1.Rows.Count- 1)
dataGridView1.Rows.Add();
dataGridView1.Rows[row].Cells[clmn].Value = openFileDialog1.FileName;
}
EDIT
I didn't notice that you are binding your datagridview :(
Ok, to solve it: use binding source, set its DataSource property to your list, then set the data source of the data grid view to this binding source. Now, the code should look like so:
public partial class frmTestDataGridView : Form
{
BindingSource bindingSource1 = new BindingSource();
List<string> datasource = new List<string>();
public frmTestDataGridView()
{
InitializeComponent();
datasource.Add("item1");
datasource.Add("item2");
datasource.Add("item3");
bindingSource1.DataSource = datasource;
dataGridView1.DataSource = bindingSource1;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
int row = e.RowIndex;
int clmn = e.ColumnIndex;
if (e.RowIndex == dataGridView1.Rows.Count - 1)
{
bindingSource1.Add("");
}
dataGridView1.Rows[row].Cells[clmn].Value = openFileDialog1.FileName;
}
}
}
Remember to use Row.BeginEdit() and Row.EndEdit() if you get this error while editing a value in a row, using DataGrid or GridEX from Janus (in my case). The sample code that Darrel Lee posted here (https://stackoverflow.com/a/9143590/1278771) remind me to use these instructions that I forgot to use and this solved the problem for me.

Categories