I’m trying to bind a list of data to a data grid, but can’t do it. I’m giving my code here.
I have made a class like this:
public class Book
{
int bookID;
string bookName;
string athourName;
public Book(int BookID, string BookName, string AuthorName)
{
bookID = BookID;
bookName = BookName;
athourName = AuthorName;
}
}
Under form load event, I wrote the following code:
private void Form1_Load(object sender, EventArgs e)
{
Book Book1 = new Book(001, "Java", "Harbart");
Book Book2 = new Book(002, "C", "Balaguru");
string[] BookArray = new string[10];
BookArray[0] = Book1.ToString();
BookArray[1] = Book2.ToString();
List<Book> Obj = new List<Book>();
Obj.Add(Book1);
Obj.Add(Book2);
dataGridView1.DataSource = Obj;
}
This doesn’t give any error, but also not showing any data in the data grid. I have a feeling I’m missing something in between. A clarification on how to bind data to data grid would be very helpful.
The
DataGridViewrequires public properties to autogenerate its columns. It will not work with fields, either public or private.Change your class to this:
That uses auto-properties but you can of course use the longhand syntax as well.