I used a datagridview in my winform application.
I load datagrid with a dataset that have 4 columns.
Next I want to add a column between column2 & column3.
How to I do this.
Thanks.
You can use Insert method on DataGridView.Columns collection. For example,
var column = new DataGridViewTextBoxColumn();
// initialize column properties
...
myGridView.Columns.Insert(2, column);
Preferably, this should happen after the data binding.
Using the Visual Studio Designer, you can simply add columns of every kind in the options of the DGV.
You can even set the position of the columns by drag&drop.
If you can't or don't want to use the Designer VinayC told you to do it the code-way.
Related
I add a button column through the code to the datagridview after assigning the datasource, it shows correctly after loading. then
Add a new row and save it to the database
Retrieve the data from the database
Populate a datatable and assign it to the datasource of the datagridview
For some reason, the button column shifts from the last to second column? Why would that happen?
Because you generating columns automatically, sure you have DataGridView.AutoGenerateColumns = true
After you change DataSource all generated columns are removed and generated again.
But column added manually stay after generated columns was removed and index of manually added column become 0 or 1.
Then again generated columns added after manually added columns
For solution you can add all columns you need manually in the order you need and set DataGridView.AutoGenerateColumns = false
Or change move button column to the place you want manually every time new DataSource is added
Although there are a lot of posts on this site about populating a gridview with objects, I can't get it working.
I have a class called Logs with 3 public properties - Time, Description and Error.
There is also a public property called logList that will return a List of Logs Objects.
And I have DataGridView in my WinForm, called myGV, with 3 columns called Time, Description and Error.
So I'm trying:
myGV.DataSource = Logs.logList.OrderBy(x => x.Time);
But my DataGridView displays nothing, even though logList does contain data.
Thanks for your work on this site!
UPDATE:
If I remove all columns from myGV it does display data. So how do match static columns to the properties in my List of Objects?
It's strange that you said If I remove all columns from myGV it does display data.... I reproduced your problem and the reason is your LINQ query is not executed. You have to call ToList() or similar method before using the result as DataSource of your DataGridView:
myGV.DataSource = Logs.logList.OrderBy(x => x.Time).ToList();
Of course, If your static columns don't have DataPropertyName matched with the properties of the DataSource, there will be more columns added to your DataGridView than you expect. For example, suppose all the Time, Description and Error are added at design time without assigning any DataPropertyName and yourDataGridView.AutoGenerateColumns = true (by default), if you assign the DataSource of your DataGridView as above, your DataGridView may have 6 columns at all, instead of 3. So you can assign the DataPropertyName of your added columns before assigning the DataSource for your DataGridView, something like this:
myGV.Columns["Time"].DataPropertyName = "Time";
myGV.Columns["Description"].DataPropertyName = "Description";
myGV.Columns["Error"].DataPropertyName = "Error";
myGV.DataSource = Logs.logList.OrderBy(x => x.Time).ToList();//This should be called at here after all the DataPropertyNames are initialized.
I recommend you to set myGV.AutoGenerateColumns = true (by default) and remove all the added columns, just let the DataGridView auto-generate columns for you.
After you manually add the columns, you have to make sure you update the DataPropertyName of each one of them:
Click in the little arrow on top of your DataGridView, to display the Control's Tasks.
Click on Edit Columns.
For each of your columns find the property DataPropertyName and change them to Date, Error and Description and whatever other names you have used for your columns.
Make sure these match with your Properties in your Logs class.
OrderBy() returns IOrderedEnumerable<> type of data, that are not bindable to DataGridView.
So you have to cast them to a Binding Source.
Use ToList() method like
"OrderBy().ToList()" to bind your gridview.
dataGridView1.DataSource = studList.OrderBy(a => a.Age).ToList();
It is working
For more info to bind DataGridView visit dataGridView binding
Howdy, using vs2008 winforms.
I want to be able to use a slightly customised datagridview but cant think of a way to do it.
i have
1. a sqldataadaptor fill a dataset
2. a binding source bound to the dataset
3 a datagridview with the bindingsource set as the datasource.
I want the binding to allow sync between the dataset and datagridview, so i can edit data and then update to database with sqldataadaptor. update.
I want to show some custom columns that are calculated results.
And i want to show a final bottom row that is totals of all the columns in the DVG.
My problem is once the DGV is bound i cant add a custom column or row, it wont let me.
I know i could add it directly to the dataset that is the underlying datasource but then by changing the structure of the dataset i cant update to a database once edits have taken place.
or can i ???
Can someone tell me how i can add my custom columns and a final total row to a bound DGV.
Also while im here, if i click on the top of a column to sort on it, in a bound DGV, will it also re-sort the underlying dataset, so i i edit things will still stay synced ?
thanks in advance for any help
Yes, you can.
The adapter does not care about structure. It only cares about column names used in the Select/Insert/Update/Delete commands. You can add custom columns, expression columns, columns for subtotals, columns for totals, or whatever you need. Even change the order of the columns. I do advise adding a sort column, so you can keep the custom rows in the proper place when you or the user sorts.
You can do the same thing for custom rows. When you update through the adapter, you handle the RowUpdating event and set the SqlRowUpdatingEventArgs.Status to SkipCurrentRow for these custom rows. I strongly advise creating a row type column so you know which rows to skip when updating. (You can also use the sort column's value as a key to skip rows.)
There are a couple of articles on MSDN or KB that illustrate how to add total rows.
"How to sum the fields in a Windows Forms DataGrid control and then display the calculated totals in a footer by using Visual Basic .NET" at http://support.microsoft.com/kb/836672.
In my experience, manipulate the data table first before binding. Do what you need to do in order to support the grid and the grid's interface. It is okay to manipulate the data, add/change/remove columns and rows, then rebind when needed.
To be able to add additional unbound columns to your DataGridView you could also set its AutoGenerateColumns property to false and then add custom columns with the following method:
dataGridView->Columns->Add(...)
To calculate the contents of the unbound columns you can handle the CellValueNeeded and CellValuePushed events but you must set the DataGridView into 'virtual mode' by setting the VirtualMode property to true in order for the eventhandlers to be invoked.
Hope this helps a little....
I have a DataGridView in a C# WinForms app that is DataBound at runtime (through Form_Load) to a custom Object.
In the design view of the DataGridView I have no columns set up.
When the Form loads the the columns are automatically created based on the data in the Custom object that it is DataBound to.
My question is how can I control the the Columns that are automatically created.
For example if I want one of the columns to be a DataGridViewLinkColumn instead of the DataGridViewTextBoxColumn that is automatically created?
The default columns are based on the data-type. I haven't checked, but for a link you could try exposing the data as Uri, but that might be hopeful. Really, if you want a specific type of column - add the columns through code and set DataGridView.AutoGenerateColumns to false.
As Andrew implies; normally something like reflection is used to generate the columns, and you'll get a column for every (browsable + public + readable) property. There is a layer of abstraction on top of this if you need, but this won't help with adding a hyperlink column.
You can pre-create your columns in the designer. If the name of the column matches the name of the property the column will end up bound to, the databinding will take care of the DGV population for you as before.
I want to add a DataGrid to a Form. When the program executes, the user enters values and I use those values in the problem. I need a similar implementation for a table with two columns and when the user enters values I use them to for calculation in the program.
There is no requirement to save these values to a database, they are just going to be used in the program.
How do I do this in C#?
In a winforms environment, you can bind strongly typed collections as the datasource; Each property of the objects in the collection makes a column (Strictly speaking, I believe it works out the properties for the type that the collection returns, rather than the individual items in it)
If you are writing a WinForms App then you can use a DataTable to store the data and a DataGridView to display it. Simply create the DataTable:
dataTable = new DataTable();
Create the columns you need programatically:
var columnSpec = new DataColumn();
columSpec.DataType = typeof(decimal); // If it holds a decimal
columSpec.ColumnName = "Interest Rate";
dataTable.Columns.Add(columnSpec);
Add the DataGridView to the form using the Designer - but don't and then once the table has been created bind it to the grid using:
dataGridView.DataSource = dataTable;
You can set the properties on the grid from the designer view.
I have done this in a read-only case where the DataTable is populated from the program and just displayed it. All the user can do is resize, reorder or set the visibility on the columns. To add new rows you'll need to hook into the RowsAdded event
Re-wording Rowland Shaw
You need not have a database to bind to the datagrid. If you have the data filled in a strongly typed or a generic collection you can bind the datagrid to the collection. The datagrid will fill the data from the collection.
It will take the property names as the columns, and the rows will display as per the rows in the collection.
If you want user input, then I think you should consider using a better grid control. The datagrid is not suitable for this purpose. I dont' remember if flexgrid (the ocx one) has been redone for .Net.
You can use a datagridview and build a datatable and add columns through your code and set the datatasource of your datagridview as this datatable and set AllowUserToAddRows in properties window of Dataggridview to true ( true is the default value ).
If you want to make the calculation after a full ro update is made then you can use RowPrePaint event or if you want the calculation to be made after the data in each cell gets updated then you can use the CurrentCellChanged event of the datagridview.
Hope this helps....