Click here to Skip to main content
15,880,608 members
Everything / DataGridView

DataGridView

DataGridView

Great Reads

by Shweta Lodha
Reducing flicker and blinking in DataGridView.
by Dukhabandhu Sahoo
This article explains how to display a loading indicator (a GIF image) in Windows Forms application when some long running task is performed in the background.
by Super Lloyd
A fully featured yet short (only 436 lines) replacement for datatables
by Ger Hayden
C++ DateTimePicker in DataGridView

Latest Articles

by kevinuni
This is an alternative for "Master Detail Datagridview"
by WyoMetz
Simple and easy paging of a WPF DataGrid with DataTable and LINQ queries
by Wade Harvey
This article shows how to use Winforms, WPF and C# to create a File Explorer Clone with Tabs and an extremely fast parallel file search utility.
by Dukhabandhu Sahoo
This article explains how to display a loading indicator (a GIF image) in Windows Forms application when some long running task is performed in the background.

All Articles

Sort by Score

DataGridView 

23 May 2012 by Shweta Lodha
Reducing flicker and blinking in DataGridView.
8 Apr 2011 by Wendelius
As already said, if you modify the contents of the same datatable in another window the datagridview binded to that datatable will be updated.If you want to do programmatic operations, one way that you add a new event in the frmNewBook, for example:public event System.Action...
7 Dec 2017 by Dukhabandhu Sahoo
This article explains how to display a loading indicator (a GIF image) in Windows Forms application when some long running task is performed in the background.
8 Jan 2019 by RickZeeland
Instead of sending lots of commands you could try sending one command using the "IN" clause, see example here: SQL IN Operator[^]
27 Jun 2014 by Super Lloyd
A fully featured yet short (only 436 lines) replacement for datatables
15 Oct 2010 by Ger Hayden
C++ DateTimePicker in DataGridView
15 Apr 2011 by OriginalGriff
Try: DataGridViewRow r = dataGridView1.SelectedRows[0]; if (r != null) { r.ReadOnly = false; }
5 Oct 2011 by André Kraak
You will probably want to respond the to the DataGridView.SelectionChanged Event[^].In its handler check if a single row has been selected then get the values from that row and place them in the text boxes.private void DataGridView1_SelectionChanged(object sender, EventArgs e){ if(...
2 Mar 2012 by PWFisch
Drag drop multiple selected rows of datagridview with left mouse button
7 Jun 2012 by VJ Reddy
If your purpose is to find the Cell in the DataGridView containing a given Text, then I think it is better to use the Rows and Cells collection of DataGridView to generate a List of DataGridViewCell which contain the given text. Then on a button click set the CurrentCell of DataGridView to the...
14 Aug 2012 by Clifford Nelson
I am trying to bind a dynamic object to a DataGridView using a BindingSource. Is there some way to bind a DataGridView, so some other grid to a dynamic object? I cannot even hard code columns and get the binding to work.UpdateWhen talking about dynamic object I am talking about an object...
21 Sep 2013 by Mike Meinz
A Google search found this[^] answer.It looks like you have to suspend binding and then resume binding. I adapted example from the web page found at the link above.CurrencyManager currencyManager1 =...
3 Nov 2013 by CHill60
Firstly make the cells that you are interested in wrappable by setting the default style ... dataGridView1.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;Note I've chosen only the first column here [0]. If you wanted all cells to wrap then use...
2 Apr 2019 by BillWoodruff
You gotta drill-down; I'd use Linq: private List DGViews; private void Form1_Load(object sender, EventArgs e) { DGViews = tabControl1.TabPages .Cast() .SelectMany((TabPage tab) => tab.Controls.OfType()) .ToList(); } Since every...
23 Oct 2010 by shakil0304003
I think there is some problem in your code. Write something like this decimal mon = 0; decimal comPrice;for (int i = 0; i
13 Jan 2011 by Simon_Whale
import the excel data and run an outer join queryAccess Outer join query[^]
19 Feb 2011 by Abhinav S
This[^] example should definitely help you out.
16 Mar 2011 by Henry Minute
If you want to use your Enter_DataGridView in other projects, it should be declared as public. public class Enter_DataGridView { ................... }
11 Feb 2012 by Wonde Tadesse
Google will give you lots of articles. Perhaps you should search it before asking quesion. Anyways here is what found for you.Using The Silverlight DataGrid[^]
7 Apr 2012 by VJ Reddy
The CellMouseEnter event of DataGridView control can be used for this purpose as shown belowprivate void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { //Skip the Column and Row headers if (e.ColumnIndex
17 Apr 2012 by VJ Reddy
The Merge method of DataTable can be used for this purpose as shown below:Private Sub Main() Dim people As New DataTable() people.Columns.Add("Id", GetType(Integer), Nothing) people.Columns.Add("Name", GetType(String), Nothing) people.PrimaryKey = New DataColumn()...
16 Jun 2012 by Dave Kreskowiak
You don't need the Panel at all.Create your own DGV class by inheriting from it, then override the OnPaint method with something like:Public Class MyDGV Inherits DataGridView Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs) ...
9 Nov 2012 by miteleda
Copy DataGridView contents to clipboard regardless of current selection.
12 Mar 2013 by OriginalGriff
First off, that test will never work:theRow.Cells[colIndex].Value.Equals(null)Translates to:Object o;o.Equals(null)If the object being tested is null, then there is by definition no instance to call the Equals method on, and since it cannot be static, a null value will always throw an...
24 Oct 2013 by Sergey Alexandrovich Kryukov
In essence, this is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to...
17 Nov 2013 by Hazem Torab
Generate reasonable sample data for you GridView without using databases.
12 Jun 2014 by Sergey Alexandrovich Kryukov
You cannot directly do it, because columns of the DataGridView are not controls. You can try to achieve desired effect by modifying the property Cursor of this control, depending on the current location of the mouse withing the control, using columns widths to calculate the location of each...
25 Mar 2015 by TarikHuber
Use STT (SQL Table Toolkit) to bind WinForm Controls to a DataGridview and to define ComboBox data sources
14 Jan 2017 by Miguel Diaz Kusztrich
Custom DataGridView that allows you to add formulas to cells
4 Apr 2019 by Richard Deeming
Here's a helper method I find useful in this sort of situation: public static class TreeExtensions { public static IEnumerable SelectRecursive(this IEnumerable source, Func> getChildren) { if (source is null) throw new...
14 Jul 2020 by CHill60
In your example code you appear to be trying to do both methods. Pick one. See the comment from @Richard-MacCutchan. If you go down the datatable route dgvOne.DataSource = dt then add 12 blank rows to the datatable before assigning it to the...
1 Jul 2023 by Graeme_Grant
Microsoft Excel moves the cursor down a row if the enter key is used. I would recommend using this as it is familiar. However, to move the cursor right, not down, on using the Enter key, it is possible. The following code will wrap the cursor...
22 Apr 2010 by William Winner
You probably want to override the RowPrePaint event. There is sample code at DataGridView..::.RowPrePaint Event[^] on how to paint a gradient row background if the row is selected. You would just need to modify it to your needs.[Update]Man, it took me forever to actually figure out how...
18 May 2010 by radix3
hello,I have tried to solve this query in button1 i have binded the grid with data and in button 2 i whatever u edit in the grid and hit button2 those records will be saved in the databaseusing System;using System.Collections.Generic;using System.ComponentModel;using...
21 Jul 2010 by Sandeep Mewara
Error is in this part of code:for (int i = 1; i
31 Oct 2010 by Nish Nishant
You need to load the data in a background worker thread, so your main UI thread will remain responsive while the data loads. This will let you show a loading message on the dialog/form while the user is waiting for the data to load.
24 Nov 2010 by Toniyo Jackson
As i understand ur question,Select count(*) from tablename where paidDate >= '01/11/2010' and paidDate
24 Nov 2010 by Sandeep Mewara
Well, first of all design the datavase tables such that you can capture all data.For now, assuming once a transporationID is related to a ClientID, whole month is used. It would give something like, transportation cost of that transportationID * 30 days!Thus, to be generic, you need to...
5 Dec 2010 by wILDFriCK
Hi all,How can I change the RightToLeft property for the column of a DataGridView and not the whole DataGridView.i.eI want my DataGridView to contain two columns, one RightToLef and the other one LeftToRight.Solution found:Handle the DataGridView.CellPainting event and add the...
29 Dec 2010 by Ole Morten Heien
Hi all.I have a question for you regarding EntityFrameWork and DataGridView. Actually this Q is more generic because it would be the same if using EntityFramework, DataSet/DataTable, Linq2Sql, etc. etc.Ok. Here goes:I have a DataGridView. This DataGridView is filled with data from a...
5 Feb 2011 by OriginalGriff
Use the DataGridViewCellValidatingEventArgs.FormattedValue property[^]
14 Mar 2011 by Sandeep Mewara
:doh:I am sorry but there is no quick question here. This is your college assignment, you should put some effort.We expect you to put some time in trying the issue that you are facing and then some time in formulating the question while posting here. I see both missing. :doh:Here is...
27 Mar 2011 by Albin Abel
You can do in LinQ. You can even submit multiple changes at once.From the grid view event get the key for the row, which can be used to query the linQ object.For example assume you have Products table in your dataContext class. 1)Instantiate it. 2) Get Product LinQ object you...
6 Apr 2011 by Henry Minute
When you define your columns set the DataPropertyName property to the required column from the dataset. MSDN Example[^].
15 Apr 2011 by a1mimo
if you want the row ReadOnly property to be false then use thisdataGridView1.CurrentRow.ReadOnly = false;
18 Apr 2011 by DipaliKolhe
Use gridView.Rows.Insert(0, gridviewRow)
13 Jul 2011 by wizardzz
I casted sender as DataGridViewComboBoxEditingControl. I was unaware of this object, but it seems to have a row property that I needed.
16 Jul 2011 by Marc Clifton
Not that I would normally do this, I'm actually just goofing around with .NET's DataGridView...but I have class, Person, that has a List as a property.I'm creating a BindingSource with a DataSource=new List();OK, fine, the grid displays the properties in Person. But...
5 Oct 2011 by markypm
hi guys,so i want the user to be able to select multiple rows. i've done this by setting multiselect = true and selectionmode = cellselect.. the problem is the selections spans multiple rows.. i want the user to only be able to select on the row where he/she first mousedown..any suggestions?
5 Oct 2011 by Sergey Alexandrovich Kryukov
It sounds like you want multi-select and single-select at the same time :-). Not so, of course: what you want is clear: to have arbitrary cell selection within the single row.Such DataGridViewSelectionMode option does not exists, and I think, for a good reason: the users expect something...
17 Nov 2011 by Wayne Gaylard
Just pass the id for the new member in the constructor of the edit form, and use it to select the right person in the datagrid.Hope this helps.In reply to your comment.Say your second form was called EditForm, then you would create a constructor in this form that takes an int...
17 Nov 2011 by OriginalGriff
No. Sorry.But - you can tell yourself where it is.If you can cause a failure in development, then put a breakpoint on the MessageBox line, and examine the exception itself. SQL server is pretty good at reporting problems, and it can help you quite a bit with what it causing it. You can...
20 Nov 2011 by Mehdi Gholam
I have found a possible solution here : http://www.dotnetmonster.com/Uwe/Forum.aspx/winform-data-binding/1042/BindingSource-Filter-fails-when-datasource-derives[^]
5 Feb 2012 by Shahin Khorshidnia
Hello,I hope it helps:Following code generates a "Winform" and a number of "TextBox"es dynamically.private void MyGrid_DoubleClick(object sender, EventArgs e){ if (this.MyGrid.SelectedRows.Count == 0) return; System.Windows.Forms.Form form = new...
23 Feb 2012 by Maciej Los
First of all you need to understand Scope of variables[^]And here[^] you'll find complete example (ReadXml & WriteXml).
27 Dec 2017 by Itz.Irshad
Hi All,How we can copy one or more than one rows from a data grid view to other data grid view on same form. Here, I've searching option which search from the first grid and if found some matching rows then copy them to 2nd grid. How I can achieve this ?Thanks
14 Aug 2012 by Clifford Nelson
Finally gave up using DynamicObject. Created a DataTable instead: public static DataTable CreateTable(IEnumerable model){ var Good = imageToByteArray(Properties.Resources.Check16); var Bad = imageToByteArray(Properties.Resources.Block16); var table = new...
5 Jan 2013 by Reza Alipour Fard
HiI test you code it execute without error.Please attend to bellow point:1)This code is OK.dataGridView1.CurrentRow.Cells[YourColumnNumber].Value = DateTime.Now;2)The first column number is zero, therefore if you want add date to third column you must use from 2 az...
12 Mar 2013 by Abhinav S
You can get the last row cell value as described here[^].Once you have this value, simply do string.contains[^] on this text.
17 May 2013 by Mayur Panchal
I think u should handle OnPreviewKeydown event to catch 'Enter' key in user control and write your stuff there.
3 Jul 2013 by santosh_131
If the cell has to be checked for both the conditions try the following code:If (e.ColumnIndex = 0) Then 'checking value for column 1 only Dim cellData As Integer IF Not DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value is DBNull.Value Then If...
3 Aug 2013 by Aarti Meswania
create a custom control inherit from gridview override below two methods. and use this custom gridview instead of datagridview.Protected Overrides Function ProcessDataGridViewKey(ByVal e As System.Windows.Forms.KeyEventArgs) As Boolean Try If e.KeyCode =...
8 Aug 2013 by Sergey Alexandrovich Kryukov
In addition to on-line tools for translation (the one referenced in Solution 1 seems to be one of the best), there is a really good and comprehensive off-line open-source solution.This is ILSpy:http://www.ilspy.net/[^],http://en.wikipedia.org/wiki/.NET_Reflector[^].First, you need to...
24 Aug 2013 by Dave Kreskowiak
That code does not update a DGV. It updates a DataTable, which you then have to bind to a DGV.You can find an example of using the OleDataAdapter here[^].
16 Sep 2013 by Maciej Los
Test it:DECLARE @lessons TABLE(LessonID INT IDENTITY(1,1), LessonName VARCHAR(30))INSERT INTO @lessons (LessonName)SELECT 'lesson A'UNION ALL SELECT 'lesson B'UNION ALL SELECT 'lesson C'UNION ALL SELECT 'lesson D'--UNION ALL SELECT 'lesson E'DECLARE @subject_lesson TABLE...
18 Nov 2013 by bowlturner
You don't seem to be using SchedStart correctly in either of them. I am assuming that you are meaning to use the column name in all 4 places. in your first example you are saying where '2013-11-18' = 11; that is why you get null.what you'd want is where v_Month = MONTH(SchedStart). ...
19 Nov 2013 by T-Maz
public partial class Form1 : Form { public Form1() { InitializeComponent(); dataGridView1.Rows.Add( 1,2); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if...
19 Dec 2013 by agent_kruger
i have developed an application and it is running fine. But when i uploded the software to one of my client machine it gives the following error.system.security.permissions.hostprotectionattribute from assembly mscorlib.I Am using c# windows application and database is access.Note: On...
24 Dec 2013 by Maciej Los
Use one of DataGrigViewCell's method[^], for example OnLeave, and force datatable to re-calculate Total using Compute method[^].
13 Jan 2014 by OriginalGriff
Perhaps it would help is you added the new row to the table?DataTable.NewRow[^] just creates a new blank row with the correct schema / columns...
14 Feb 2014 by OriginalGriff
Try:SELECT CASE WHEN field=0 THEN field ELSE 0 END AS Above FROM MyTable
26 Feb 2014 by Sergey Alexandrovich Kryukov
The Solution 1 will help to formally compile the application, but it will leave it defective. You need to address the root cause of the problem. Think why it is not allowed to work with unassigned variables. A dummy value will allow your code to skip both if ... else if statements of your code,...
9 Mar 2014 by AndrewCharlz
Hi, Now You have Table : Vehicles, Months, Fuel_Bill, Lubi_BillI have one best idea to do this.Now these tables are related let me consider Vehicles Table have the Collection of various Vehicles. and each vehicle will have a unique id which is the primary key.secondly ill give u...
29 Mar 2014 by Maciej Los
Have a look at example:--TDCREATE TABLE #tblTicketDetail( TicketID INT, IssuerName NVARCHAR(30), TicketDescription NVARCHAR(30))--ENCREATE TABLE #tblEngineer( EngineerID INT IDENTITY(1,1), [Name] NVARCHAR(30))--TECREATE TABLE...
21 Apr 2014 by ccalma
Use DataGridView1.CurrentRow.Cells("name").Value orDataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells("name").ValueDim rowContent As String = String.Empty For columnCounter As Integer = 0 To DataGridView1.ColumnCount - 1 rowContent = rowContent & " " &...
25 Apr 2014 by Dave Kreskowiak
It takes forever because you're populating each cell, individually. That's 10,000 calls to set each cell. The DataGridView is NOT Excel! You're trying to force the DGV to do something it was not designed to do.On my machine, your code takes less than 1 second to run. What are you running...
17 Aug 2014 by OriginalGriff
Two possibilities here:1) RowIndex is out of the range, 2) Cells is out of the range,If it isn't the RowIndex, then it has to be the Cells - are there any?Or...should that be dataGridView1 at all? The method name implies the control is called ExcelDGV...Use the debugger to look at...
28 Sep 2014 by Dave Kreskowiak
Yeah, there's a faster way. DON'T LOAD IT UP WITH 50,000 RECORDS!!Honestly, who in their right mind is going to want to look at ALL Of those records?? NOBODY!!Use paging and filtering techniques to help the user get the dataset down to what THEY want to see, NOT what YOU want to throw...
28 Sep 2014 by Raul Iloc
1.By default, in using the GridView control for manipulating a large amount of data (a few hundreds of rows), the performance is very low, and if the number of rows increases to several hundreds or several thousands, the web page becomes useless. Note that there is the loading time from DB, then...
1 Apr 2015 by Maciej Los
I'd suggest to read this: Many Questions Answered at Once — Collaboration between Windows Forms or WPF Windows[^] and this: Transferring information between two forms, Part 1: Parent to Child[^]
4 May 2015 by Peter Leow
Check this out DataGridView – Stacked Header[^]You have to translate it into vb.
28 May 2015 by CHill60
Columns - in the designer click on the property ColumnHeadersDefaultCellStyle and select Layout, Alignment = MiddleCenterFor the data fields do the same for DefaultCellStyle
29 Jun 2015 by Animesh Datta
You can simple use Loop to clear the column value from DataGridViewforeach (DataGridViewRow myRow in dataGridView1.Rows) { myRow.Cells[0].Value = null; // assuming you want to clear the first column}
4 Aug 2015 by Richard Deeming
Using a properly parameterized query will fix the SQL Injection[^] vulnerability in your code, and also fix the error you're seeing:using (SqlConnection connection = new SqlConnection("-YOUR CONNECTION STRING-"))using (SqlCommand command = new SqlCommand("INSERT INTO Bills (ItemName)...
25 May 2016 by Alan N
-1 is the index of the header row and CellValueChanged events with RowIndex = -1 are raised when a Column's HeaderText property changes. You probably have no interest in these events and can ignore them by testing for RowIndex = -1 in the handler. For example:Private Sub...
25 May 2016 by Dave Kreskowiak
The solution is kind of easy. The RowIndex is -1 because there is no selected row. So, just check for that and if it's -1 return, don't do anything.Next, you have to make sure that the index you're getting is actually a valid index for the range. So, check for it before you try to use an...
21 Oct 2016 by Suvendu Shekhar Giri
One of the way is to, instead of adding rows to the datagridview, add datarows to a datatable and then once datatable is ready make it the datasource of your datagridview.Something like-DataTable table = new DataTable();table.Columns.Add("Name", typeof(String));table.Columns.Add("...",...
31 Oct 2016 by Mehdi Gholam
Try setting the cell style not the column :DataGridViewCell.Style Property (System.Windows.Forms)[^]datagridView1[1,1].Style.ForeColor = Color.ForestGreen;
3 Jan 2017 by Wendelius
There are quite a few problems to fix. Consider the following alternativestring sql;DataSet dsa = new DataSet();DataTable dt = new DataTable();dsa.Tables.Add(dt);using (OleDbConnection connection = new OleDbConnection(connectionString)) { sql = @"SELECT * FROM [Sales Record]...
10 Apr 2017 by CHill60
Loading 25000 items into a User Interface is just silly. That is the politest way I can put it. WPF collections? I think your friends are talking rubbish. How to speed up the load times? 1. You should implement some sort of paging - for example only load the first 40 items until the User...
27 Aug 2017 by Patrice T
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone. A single quote in a name and your program crash. If a user input a name like...
19 Sep 2017 by OriginalGriff
Move the bracket, and don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead. When you concatenate strings, you cause problems...
25 Oct 2017 by Richard Deeming
Try something like this: private DataRowView GetCurrentRowData() { if (JOGridView.CurrentCell == null) return null; int rowIndex = JOGridView.CurrentCell.RowIndex; if (rowIndex == -1) return null; return JOGridView.Rows[rowIndex].DataBoundItem as DataRowView; } ...
18 Nov 2017 by asiwel
Construct a confusion matrix or crosstab for binary or multi-level classifier training or validation data in C#
9 May 2018 by Maciej Los
Maciej Los: Does your DataGridView is bind with datasource? If yes, what kind of datasource: BindingSource, DataTable, DataSet? Primo Chalice: It is DataSet In this case, the simplest way is to use: DataSet.WriteXml Method (System.Data)[^] and DataSet.ReadXml Method (System.Data)[^]
31 Jan 2019 by OriginalGriff
The VB For loop runs from the start to the end value inclusive - so this: For index As Integer = 0 To 3 Console.Write(index.ToString & " ") Next Will print 0 1 2 3 So your code For Z1 = 0 To DataGridView1.RowCount will work from the first index to the one after the last index inclusive,...
4 Feb 2019 by OriginalGriff
Your first problem is: you have completely the wrong approach. Quote: When a user has many thousands of items selected in a DataGridView (we're talking hundreds of thousands or even millions) Do you seriously think that any user will conscientiously select that many records? That he will even...
8 May 2019 by OriginalGriff
Not like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead. When you concatenate strings, you cause problems because SQL receives...