So I am using the DataListView variant from BrightIdeasSoftware for my c# project.
I use buttons to change the view of the DataListView. When a button is pressed the following is executed:
olv.DataSource = null;
olv.AllColumns = colList;
olv.RebuildColumns();
//Fill OLV with data
olv.DataSource = dt;
The first button creates 1 column and changes the view to View.Tile;.
The second button creates 4 columns and changes the view to View.Details;.
The new columns are shown immediately but it takes about a second for the data to show up in the list. It takes even longer when I rebuild a larger amount of columns.
When I run my application it builds the view with 4 columns in View.Details instantly.
Only when I switch from the first button view to the second button view it hangs for a moment.
In debug mode I noticed that RebuildColumns() is the one that hangs.
But if I leave olv.DataSource = dt; out, code after RebuildColumns() is executed immediatly.
Can someone explain to me why this is happening?
Thanks
First of all it is not clear to me if the lists that you are switching between use the same DataTable (I assume that's the type of your dt object). If source is identical then you needn't add and remove columns, you can set OLVColumn.IsVisible. That's faster.
Second, setting ObjectListView.DataSource = null won't remove items from the list (you need ObjectListView.ClearObjects for that), but what that will do is invalidate the internal DataSourceAdapter.CurrencyManager which will block any item updates until ObjectListView.DataSource is specifically set again. Setting the data source will add items to your list (calls ObjectListView.BuildList) which might be expensive if your source is large.
In conclusion:
If you just switch between lists with shared datasource then:
foreach (var column in this.dataListView.AllColumns)
column.IsVisible = true;
// call this only when tampering with columns
this.dataListView.RebuildColumns();
// if you need to add/remove items, same philosophy, partial instead of
// complete update use filtering instead of DataSource reset
If lists do not have a common datasource and therefore columns totally differ, then it is a price you have to pay, rebuilding columns and items, but you could escape with a TabControl for instance. You could switch between lists without having to reset DataSource all the time. That should be a one time experience.
Related
I have an input enabled DataGridView bound to a BindingSource which has a SortableBindingList as DataSource.
There is no direct connection to the database. The list is read once from the database beforehand. After the user is done with editing he can choose either to save the changed data to the database or not.
The list has 2 fields:
"Type" (enum)
"Path" (string)
As I want to use a ComboBox for the user to select the "Type" I add an additional column "TypeCbx" which is bound to the enum values. Initially, all "Type" values from the list are copied to the column "TypeCbx" and for changes, the value of "TypeCbx" is copied back to "Type" in the event ...CellEndEdit().
Furthermore, I have 2 button columns included:
"Browse" button: opens a FolderDialog for the user in order to adjust the actual row and set the column "Path" and (if it is a new row/entry) a default value to "Type"
"Remove" button: removes the row/entry from the DGV
This worked as long as I used an unbound DataTable in which I had the following code for the button "Browse":
private void dgvPaths_OpenFolderClick(DataGridView sender, DataGridViewCellEventArgs e) {
string newSelectedPath = Helper.FileBrowserDialog("Select folder", LastSelectedPath);
if (newSelectedPath != null) {
LastSelectedPath = Helper.CleanPath(newSelectedPath);
if (dgvPaths.Rows[e.RowIndex].IsNewRow) {
// --- variante old: unbound datatable ----------------------------------------
DataGridViewRow row = (DataGridViewRow)dgvPaths.Rows[0].Clone();
row.Cells[dgvPaths.Columns["Path"].Index].Value = LastSelectedPath;
row.Cells[dgvPaths.Columns["Type"].Index].Value = LibraryPathType.Movies;
row.Cells[dgvPaths.Columns["TypeCbx"].Index].Value = LibraryPathType.Movies;
row.Cells[dgvPaths.Columns["TypeCbx"].Index].ReadOnly = false;
dgvPaths.Rows.Add(row);
dgvPaths_CellValueChanged(sender, e);
} else if (dgvPaths.Rows[e.RowIndex].Cells["Path"].Value == null || LastSelectedPath != dgvPaths.Rows[e.RowIndex].Cells["Path"].Value.ToString()) {
dgvPaths.Rows[e.RowIndex].Cells["Path"].Value = LastSelectedPath;
dgvPaths.Rows[e.RowIndex].Cells["TypeCbx"].ReadOnly = false;
dgvPaths_CellValueChanged(sender, e);
}
}
}
Now, with the bound DataSource, the line dgvPaths.Rows.Add(row); no longer works. So I adjusted the code as follows:
// --- variante new 1: bound list, working on dgv -----------------------------
dgvPaths.Rows[e.RowIndex].Cells["Path"].Value = LastSelectedPath;
dgvPaths.Rows[e.RowIndex].Cells["Type"].Value = LibraryPathType.Movies;
dgvPaths.Rows[e.RowIndex].Cells["TypeCbx"].Value = LibraryPathType.Movies;
dgvPaths.Rows[e.RowIndex].Cells["TypeCbx"].ReadOnly = false;
dgvPaths_CellValueChanged(sender, e);
Issue 1:
Now, the data is written into the row of the DataGridView but the DataGridView does not interpret it as an input and therefore it is not really added - it still is a "new Row" waiting for input. I need to manually go into the Path Column of the row and press a key in order that the DataGridView accepts it as a valid entry and shows a new "new Row" line.
=> How can I inform the DataGridView that programmatically entered data should be handled like a user input?
Issue 2:
Furthermore, when I manually enter an entry in the DataGridView and click in the "Path" column between the added line and the new "new Row" line, a first chance exception is thrown.
=> What is the reason for the first chance exception?
Then I've read that you should not manipulate the DataGridView but instead the BindingSouce or BindingSource.DataSource, which I tried with by changing the code to this:
// --- variante new 2: bound list, working on datasource ----------------------
Library.Current.AddDirtyPath(LibraryPathType.Movies, LastSelectedPath);
Issue 3:
Hereby, I also get a first chance exception when this entry is added to the source list.
=> What is the reason for the first chance exception?
What is the correct approach here?
=> Do I need to manipulate the rows of the DataGridView or the entries of the BindingSource or the entries of the BindingSource.DataSource?
Issue 4:
The bound DataGridView threw another exception when loading the DataSource and there is no enum value for "0" (I guess for the "new Row" line). Therefore, I needed to add a dummy enum value which is set to "0" to my enum value list which I need to skip again for the actual ComboBox selection values. It works but it messes up the code.
=> Is it possible to avoid this dummy value, at all?
--- U P D A T E ---
After reading Caius recommendation, I have decided to update this question as I was able to follow the SBL approach and reduce the issues.
The correct approach here is to use a main "storage" SBL for all working data (which is initially filled by reading the DB) and create a filtered SBL out of it which is used as DS for the DGV where the user can work on and use sort and filter methods. By adding/updating/removing data, you have to ensure that all adjustments stay synchronous in the "storage" SBL. Then, when you want to update the DB, you use the 'storage' SBL.
Thereby only 1 issue is left: if you want to add a new line with a button column function inside the DGV itself. It fails as the state of the actual new line is changed while you are calling the add function from inside the DGV. There are 2 ways to "fix" this:
a) You need to completely(!) Clear() the SBL that is used as DS for the DGV and add the new line afterwards (according with all other existing ones from the "storage" list) back to this SBL. Thereby the state of the new line is also changed but as it is completely removed the state is also cleared. After this you need to Refresh() the DGV. Hereby, you will lose focus of the actual cell.
b) You use a hidden button outside of the DGV by btnAdd.PerformClick() which calls the add function in which you do not need to Clear() the SBL that is bound to the DGV. This seems strange but it works (whyever) and you keep the focus on the "new line" row (not on the added one).
All other functions like updating and removing an existing DGV line can be called by additional button columns within the DGV itself without issues.
The enum issue is not an issue as it is common to use a dummy zero value for empty entries. If I find out, how to get rid of the dummy value, I will update this question accordingly.
In order to fill the combobox column without a split between display and value columns you only need to ensure that the DataPropertyName of the combobox column is set like the DB column name.
--- U P D A T E: 2 ---
I have created a detailed video (tutorial) about my approach:
https://www.youtube.com/watch?v=W_afaNf7nz8
From 1:31:20 I show the difference between adding a new line by an external and an internal button and also the strange behaviour of using the method directly (=> error) or triggering an external button which uses the same method (=> no error).
What is the correct approach here?
You have a datagridview
You bind its DataSource to a datatable
You have a datagridviewcombobox
You bind it's DataSource to a completely different datatable
You tell the combo which columns, from its own datatable, are to be used for display, value and which column in the table that the grid is bound to, shall be updated/used for deciding which value to Show
var gdt = new DataTable();
gdt.Columns.Add("FileType", typeof(FileType));//enum
gdt.Columns.Add("Path");
gdt.Rows.Add(FileType.Text, "c:\my.txt");
var fdt = new DataTable();
fdt.Columns.Add("Val", typeof(FileType));//enum
fdt.Columns.Add("Disp");
foreach(FileType t in Enum.GetValues<FileType>())
{
fdt.Rows.Add(t, t.ToString());
}
//now wire it up
datagridviewWhatever.DataSource = gdt; //makes columns
var c = new DataGridViewComboBoxColumn();
c.DisplayMember = "Disp"; //name of column in fdt to use for show
c.ValueMember = "Val"; //name of column in fdt to use for value during lookup/set operations
c.DataPropertyName = "FileType"; //name of column in gdt that this combo shall show/set
c.DataSource = fdt; //set DataSource last (performance reasons)
Combo will now, for each row, get the value in gdt.FileType (eg FileType.Text), lookup the value in its own table fdt.Val, use the related value in fdt.Disp (eg "Text") to show in the list. If the user chooses a new list item (eg "Excel") it goes the other way, get the relevant Val (eg FileType.Excel) chosen and push it into gdt.FileType
I've never actually done it with enum typed values; can't see why it wouldn't work but if it gives trouble it might be simpler to switch to using ints instead of FileTypes - make all your typeof() calls typeof(int) and cast the FileType t to int in the foreach when adding it to the row collection.
Finally, when you're down with this as a concept I recommend throwing it all away and doing it using the visual designer - it will make a much better, nicer, easier to use job of it:
add a DataSet type file to your project
open it
if there is a database somewhere backing all this, right click on the design surface and choose Add TableAdapter, enter the connection string, choose a query, that returns rows, put SELECT * FROM MovieFiles WHERE ID = #id or whatever, call it FillById/GetDataById, finish
if there isn't a database backing all this just right click the surface, add a datatable called MovieFiles, right click it and add columns like FileType (set type to int in property grid), Path etc
right click a blank space and add another datatable called FileTypes, put a string column called Disp and an int column called Val (sounding familiar?)
save and switch to Forms designer. Open Data Sources tool panel (View menu.. other windows submenu)
Drag the MovieFiles node out of data sources and into the form. A datagridview appears as well as a bunch of stuff in the bottom tray. The grid is already correctly binded to the DataSet that contains the MovieFiles table. You can see all the code VS is writing for you in the Forms.Designer. It looks a lot like the code I put manually above
Edit the columns of the datagridview, change the file type column to be a combobox type, set the DataSource to the FileTypes table, DisplayMember to Disp, ValueMemberto Val. Check the DataPropertyName is still FileType in movies - this should also be familiar as it's the visual version of the code above)
the only thing left to do is put some code in the constructor that fills the FileTypes table from the enum (or to be honest, just make a table in the DB called FileTypes, have an int and a string column, add a tableadapter, select them.. that way you don't have to recompile the whole program when you add a file type)
Why do I advocate using these visually designed datatables rather than code ones? Because they're so much nicer in every single way. They have logical methods and named properties for columns, they just work with LINQ and they behave like .net classes that are collections of POCOs not 2D arrays of object that are indexed by string and need casting to make them useful. DataTable are awful to work with in comparison. They wrap around basic DataTable and do expose them but follow a rule that if you've exposed it, you've probably gone wrong
//no; using .Tables puts you back in "world of pain"
var p = (string)datasetX.Tables["MovieTypes"].Rows.Cast<DataRow>().First()["Path"];
//yes - using named property for MovieTypes is good, LINQ works, Path is a string property etc
var p = datasetX.MovieFiles.First().Path;
In my winforms app, I have an existing datagridview. There's a background worker that fetches data from a database and refreshes that datagridview's contents once every minute.
OK, now I have a child form in that app. When the user presses a button, I want to pop up another child form to the user, showing them a datagridview that is an exact copy of the first one, so that they may select a single row.
(NOTE: The main form/app has quite a few tabs. I have thought about instead using a column of checkboxes on the first datagridview, in cooperation with the first child-form's button, in order to accomplish this. But I think this method I'm working on will make life easier for the users.)
To quickly grab a copy of all of the rows of the first dgv, I was going to do this:
DataGridViewRowCollection rawrowcollection = null;
this.Invoke(new MethodInvoker(delegate ()
{
rawrowcollection = ParentForm.dgvIncidentTimeline.Rows;
}));
(And then, I'd check to see if the resulting collection was null... loop through the collection so as to create/ populate a List... and then loop through that to populate the second/fresh datagridview.)
My only concern is that... what if I try to read from that table and it's in the middle of doing its once-per-minute clearing-and-updating of that datagridview? Granted, this should be a very FAST process. And we're doing a read here, which I don't think would PREVENT the clearing/updating from occurring (would it?) But we could end up with partial data in the final dgv.
I thought about temporarily setting the parent dgv to readonly before doing the read...and then setting it back after doing the read. ?? And then I'd have to just plan on my once-per-minute background operation possibly throwing an exception if it tries to clear and update while we've got that dgv effectively "locked" like this??
Your thoughts??
Thanks!
I have created a WinForm that takes data from another application and saves it in a database. I use a BindingNavigator (I dragged the dataset table onto my form and got a navigator, bindingsource and more) to display and navigate through the records.
When records are added to the dataset/table the BindingNavigator doesn't update itself with the new info right away. It is like nothing was added.
I have to click on the BindingNavigator's next item, previous item or things like that so it will refresh itself and show the correct number of items.
Can someone tell me how I programmatically tell the BindingNavigator to show the updated values?
I have tried a lot of things but nothing has worked.
EDIT
I figured out what was going wrong. I was running on a different thread than the form.
Code that worked for me:
this.tableAdapterManager.PieceTableAdapter.Insert(ints[4], ints[2], ints[6], ints[8], ints[10], ints[12], ints[14]);
this.tableAdapterManager.UpdateAll(this.slicerTestDBDataSet);
this.pieceBindingNavigator.Invoke(new Action(() => this.pieceTableAdapter.Fill(this.slicerTestDBDataSet.Piece)));
Earlier I didn't use Invoke to invoke the main thread so it didn't work properly.
First thing to do is check the update and insert statements are in the command text of the tableadapter. Click on the tableadapter in the design view if the dataset and see the properties. In the properties you will see the update and insert sections with a + on the left. Expand this to see the command text. If it is empty, then go back to the right click of the table adapter and select configure. Then look at the query designer and make sure everything in the table you want to update is checked. Then finish the wizard and go back and make sure the wizard created the insert and update statements.
I have found that sometimes one textbox will accept an update and others won't. I fixed this by deleting the textbox and adding a new textbox that I would rebind.
I have built a program in WPF using Visual Basic that allows users to select from a series of items. The list of items may change as I add more items or remove older ones. Originally, I would just add and remove these items in the project code, and rebuild the executable.
Over time, however, the list of items grew and became tedious and impractical to maintain in the code. It occurred to me that it would be easier to store the items in a database table which the program can read, and the list can just be updated by adding and removing items from this database.
I have the database built, and I've added it as a Data Source. I have the data connection set up and everything is ready to go.
What I need to know is how to set the Content property of a label to a cell from a table in the database. I want to do this in the codebehind, not in markup (XAML).
My guess is that I will need to set up a sort of query with a for loop to find the cell I want.
The name of the database is ItemsDB. It contains a table called ItemsTable, and the fields in the table have a unique ID (key) with an AutoNumber data type. The column containing the data I want is named ItemLabel.
So, to sum it all up, I want a label to show the content from a single cell in the database, specified in the codebehind. Either C# or VB is fine.
EDIT
I guess I should've mentioned that the labels themselves actually function as buttons, and I don't really want to display a ListView if I don't have to. I know it's not helpful to not have any code posted, but I don't even know where to start, so there's no code to post.
Took a while longer than I expected, hope this is still useful. So, what you want to do is iterate through a collection and create a new Label for each row.
You will need a container for the Labels, I used WrapPanel, but you can use any Panel you want. I'm replacing your Data Source with a simple DataTable, you'll get the point from this:
foreach (DataRow row in YourItemsTable.Rows)
{
Label newLabel = new Label();
newLabel.Content = row["ItemLabel"].ToString();
// If you need some events, attach the handlers here
yourParentContainerPanel.Children.Add(newLabel);
}
This should be all you need.
I've encountered a performance issue with the C# DataGridView control, which appears to be the result of the unsharing of a large number of rows. The DataGridView is bound to a bindingsource, which is, in turn, bound to a dataview. I've gone through the laundry list of dos and don'ts from the MSDN info (not using rows.count() etc), but I just can't get it to play the game.
Even if I start with a brand new DataGridView control, on a fresh form, and bind it to a bindingsource that has a basic test table as its source, just showing the form seems to cause all of the displayed rows to become unshared. Then, every single row I select causes that row to become unshared. I'm wondering if I'm wasting my time trying to prevent this?
In my actual DataGridView control, it's necessary for me to have at least one column that is not visible, which contains ID values. It's also necessary for me to search all the values in this column for a matching ID. It would appear that, as soon as I attempt to iterate through the values to find a match, this is causing every single row to become unshared. Is there a way to do this that does not cause all the rows to become unshared as I search?