473,704 Members | 3,676 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# FORM: Binding DataGridView to List<T>

3 New Member
Hello all!

I found a solution to my original question, but there's still so much I don't understand about it, I thought I'd give this forum a try. At the very least, maybe it will help someone else who got stumped like I did.

It seems so simple... binding a DataGridView to a List<T>. These are the two general problems that I kept running into:

(1) When the data in the list updated, the data on the screen did not update.
(2) When I finally got data on the screen to update, if I clicked any part of the DataGridView, the following message box popped up: "An unhandled exception of type 'System.IndexOu tOfRangeExcepti on' occurred in System.Windows. Forms.dll Additional information: Index -1 does not have a value."

Here is the code that I finally got to work. Note that this code is completely contrived. I just tried to make the simplest example binding a list to a DataGridView that I could think of. Also, I am using .NET 2.0.
Expand|Select|Wrap|Line Numbers
  1.     public partial class Form1 : Form
  2.     {
  3.         private class Customer
  4.         {
  5.             private String _first;
  6.             private String _last;
  8.             public Customer(String first, String last)
  9.             {
  10.                 _first = first;
  11.                 _last = last;
  12.             }
  14.             public String first { get { return _first; } }
  15.             public String last { get { return _last; } }
  16.         }
  17.         private BindingList<Customer> customerList;
  18.         private int iCount;
  20.         public Form1()
  21.         {
  22.             InitializeComponent();
  23.             customerList = new BindingList<Customer>();
  24.             iCount = 0;
  25.             updateDataGridView1();
  26.         }
  28.         private void button1_Click(object sender, EventArgs e)
  29.         {
  30.             iCount++;
  31.             customerList.Add(new Customer("First" + iCount.ToString(), "Last" + iCount.ToString()));
  32.             updateDataGridView1();
  33.         }
  35.         private void updateDataGridView1()
  36.         {
  37.             dataGridView1.DataSource = null;
  38.             dataGridView1.DataSource = customerList;
  39.         }
  40.     }
Of special note to anyone else having problems, this binding doesn't work unless your list class has some type "properties " member function:
Expand|Select|Wrap|Line Numbers
  1. public String first { get { return _first; } }
  2. public String last { get { return _last; } }
Also, I had to make the following statements every time I updated the list:
Expand|Select|Wrap|Line Numbers
  1. dataGridView1.DataSource = null;
  2. dataGridView1.DataSource = customerList;
In addition, I had to use a BindingList<T> instead of a List<T> for customerList:
Expand|Select|Wrap|Line Numbers
  1. private BindingList<Customer> customerList;
Finally, if I used a BindingSource between the list and the DataGridView, it made no difference at all. I had all the sample problems using the BindingSource, and if I use a BindingSource in the example above, it works fine.

So, I still have a few questions about this whole thing, but to start with, am I missing the obvious?! For instance, why can't I just bind a normal List<T> to a DataGridView and have the grid view update when the list updates? When I read examples on the web, they seem so simple... but they don't work! Also, what if your list class--"Customer" in my code--has more properties methods than you want to appear in the DataGridView? Is there any way to mask them out?

Thanks a lot for any help. This has really been kicking my butt the past couple of days. Also, thanks to the folks involved with this archived thread: http://www.thescripts.com/forum/thread443793.html

That gave me the clues I needed to get my last problem solved.

Thanks again, and hopefully I'll be "talking" with some of you soon! :)
Dec 13 '07 #1
11 76212
3 New Member
Hey all,

I forgot to ask another part of my question. If I want the columns labeled "First Name" and "Last Name", I have to make the calls to update HeaderText each and every time I update the DataSource, as follows:

Expand|Select|Wrap|Line Numbers
  1. private void updateDataGridView1()
  2. {
  3.     dataGridView1.DataSource = null;
  4.     dataGridView1.DataSource = customerList;
  5.     dataGridView1.Columns["first"].HeaderText = "First Name";
  6.     dataGridView1.Columns["last"].HeaderText = "Last Name";
  7. }
That also seems strange to me.. I would think I should be able to do that just once, but then again l really suspect that I'm missing something very basic with this whole thing.

Thanks again for any help!
Dec 13 '07 #2
3 New Member
OK, I think I've finally got this thing figured out. This is just in case anyone having trouble like I was finds this thread.

First of all, a List<T> will work, but a "better" solution is to use something like a DataTable and use that as the DataSource for your DataGridView. With that DataTable, column sorting will be implemented, for instance.

Second of all, and this is a big one, whether you use a List<T> or a DataTable, after you assign your DataSource to your DataGridView, make sure that the AutoGenerateCol umns property is false:

Expand|Select|Wrap|Line Numbers
  1. dataGridView1.AutoGenerateColumns = false;
Without that, the DataGridView doesn't get updated by itself. Furthermore, without that, when it does get updated, all its values get reset. It seems so simple looking at it now, but without that, this isn't very fun.

Anyhow, I hope that helps someone. It took a while to get the hang of this, but now I've got a sweet DataGridView displaying my data. It handles sorting and everything.

Good luck to those wrestling with this one! :)
Dec 19 '07 #3
1 New Member
hi dave,

i'd just like to say that your 3 posts helped me a tremendous amount. i too had been suffering similar pains with datagridviews; no matter how simple some other tutorials on the internet made it sound, the stupid things just refused to update!!

for me the critical thing that was wrong was that i was using a bindinglist<> between my datagridview and my list<>; once i fixed this it worked!!

my solution varies from yours a bit. what i've done is create a class that extends BindingList<> and i use that as my list of objects. this gets assigned directly as the datagridview's datasource. doing it this way allowed me to use the IDE to use this class as the datasource which allows me to adjust/hide columns in the IDE rather than in code :) also i don't need to set it to null or force any updates... i just edit the list and the datagridview updates itself (never thought i'd be able to say that)
Jan 28 '08 #4
1 New Member

I've been wrestling with the same DataGridView problem that you mentioned for the last two days. Pretty new to C# but have a big project to finish.

I think we are missing part of the picture here, or at least I am - regarding events and threading scope. It's alluded to in a similar post but I didn't quite get the whole gist:

.NET Questions - (C#) updating DataGridView with a new DataSource

Turning autogenerate off didn't work for me. However that may be because I just instantiate a new datagridview object on the fly and attempt to set its datasource within the button click event of an existing form.

Jan 4 '09 #5
1 New Member
Hi to all,

I'm using List<T> objects to binding and i can't sort by any column, and also, i'd like to now how to manipute the order when before the columns are displayed
Mar 9 '09 #6
1 New Member
Thanks a lot for your help, BindingList is exactly what was needed.
Apr 27 '09 #7
1 New Member
For anyone else still struggling out there, I thought I'd make a comment in response to:
"(2) When I finally got data on the screen to update, if I clicked any part of the DataGridView, the following message box popped up: "An unhandled exception of type 'System.IndexOu tOfRangeExcepti on' occurred in System.Windows. Forms.dll Additional information: Index -1 does not have a value.""

I started having this same exact problem when I tweaked my code some and after studying what changes brought about the error I believe that it has to do with assigning your DataGridView.Da taSource to an empty List. As long as you make sure that that doesn't happen, you should be fine. Figured I'd share and maybe save somebody some frustration. Thanks for the post by the way, I found it helpful.
May 16 '10 #8
I have been harbouring a secret suspicion for some time now that Microsoft is staffed with people that are so intelligent that they don't even know that people that use their tools actually want to produce working solutions ASAP. The DataGridView is a calculated leap into the Stone Age from thie point of view. The question buzzing around in my mind is, what is the Microsoft’s grand plan, other than to loose out to Java. DataGridView is not the only area where Microsoft is making life harder for us.
Oct 15 '10 #9
9,735 Recognized Expert Moderator Expert

You typically chose your programming language based on the requirements of the application that you are developing. This means that there are situations where it is good to choose to use Java and other situations where .NET is the better choice.

Since you're posting in the C# forum, it is likely that many people here would tend to reply with ".NET is the better choice"...but it all depends on your requirements.

Anyways, the DataGridView is a control that is complicated and requires some learning to get used to it.

Microsoft is heading away from Win Form applications (where the DataGridView is used) and is pushing WPF (Windows Presentation Foundation) as the new technology to develop desktop (client) applications.

WPF does not have a DataGridView control.
It runs off of something called XAML...which is basically XML markup for specifying how your user interface is created. It is extremely flexible and very cool. (Definitely much "flashier" than Java)

You may think that the DataGridView is a difficult control to use (and you're right, new developers will have a hard time with it because it is complicated)... .

But there are better (more complicated and exciting) things out there now (and have been for a long time!)

Oct 15 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Vivek | last post by:
Hi, I wish to update the LIST<T> created in PARENT FORM from the CHILD FORM. Currently I have declared the LIST<Role> as public in my parent form. What can I do to update the <LIST>? Thanks
by: Nathan | last post by:
Hi, I am trying to bind a DataGridView to a generic List<T>. I've set up the columns in the designer, then used this code: dgv.DataSource = MyList; dgv.Columns.DataPropertyName = "Property1" dgv.Columns.DataPropertyName = "Property2" dgv.Columns.DataPropertyName = "Property3"
by: webmaster | last post by:
Pardon my being a total C# noob. I'm trying to take apart the dotNet Time Tracker dotNet C# starterkit sample application and replicate a part of the code. At a high level, I have a very simple SQL server table and stored procedure which I have no problems binding from directly from an ASP.NET control... Table BOOK
by: per9000 | last post by:
Hi, *background* I want a class containing an int (a list of sets of integer). This should be hidden for the user and he/she should be able to insert his/her favourite data structure so to be a little fancy I thought I'd do a Ctor like this: // this is the "core": private int sets;
by: Jeff | last post by:
..NET 2.0 I'm wondering if it is possible set the DataGridView.DataSource to a List<objectcollection. Where object is a class derived from the object class. If it's possible then my question is how? I ask becasue I think it's much better to use the collection directly than performing a foreach statement adding the rows to the DataGridView...
by: aramadan | last post by:
i can,t edit on the data through the grid . when i edit in each column then exit from it , it returns to its original value thx
by: Ciri | last post by:
Hi all, I've a problem with a datagridview. The data source of the control is a List<t> where t is type of a class I've created. The class (Person) has some properties like Name, Surname and so on. Now my datagridview is bounded to a collection of Person: dgwPersons=new DataGridView(); dgwPersons.AutoGenerateColumns=false; dgwPersons.Columns.Add("Name","Name"); dgwPersons.Columns.DataPropertyName="Name";...
by: Steve K | last post by:
First problem: I am specifying a format string for a Binding object like so: <code> Binding binding = new Binding("Text", item.EOBRemittance, "AmountAllowed", true, DataSourceUpdateMode.Never, 0, "{0} Selected Pages");
by: admlangford | last post by:
Hi, I have a collection of objects which I am storing in a list the object looks like this struct Person { public int age; public string name; }
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.