Binding ListT to DataGridView in WinForm
List does not implement IBindingList
so the grid does not know about your new items.
Bind your DataGridView to a BindingList<T>
instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
But I would even go further and bind your grid to a BindingSource
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
How to bind list to dataGridView?
Use a BindingList and set the DataPropertyName-Property of the column.
Try the following:
...
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Value",
HeaderText = "File Name",
DataPropertyName = "Value" // Tell the column which property of FileName it should use
};
gvFilesOnServer.Columns.Add(colFileName);
var filelist = GetFileListOnWebServer().ToList();
var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList
//Bind BindingList directly to the DataGrid, no need of BindingSource
gvFilesOnServer.DataSource = filenamesList
}
How do I bind a ListCustomObject to a WPF DataGrid?
if you do not expect that your list
will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource
this property in WPF is usually named ItemsSource
):
this.dataGrid1.ItemsSource = list;
But if you would like to replace your list
with new collection instance then you should consider using databinding
.
How to bind List to dataGridview C#
Data binding only work with Set/Get Properties, not public field.
Try to change your FileDetail
like this :
public class FileDetail
{
public string filename { get; set; }
public int openConnectionCount { get; set; }
public int closeConnectionCount { get; set; }
}
How to bind a Liststring[] to a DataGridView control?
Try this:
dataGridView.DataSource = userNphotoValues
.Select(arr => new { UserName = arr[0], PhotoPath = arr[1] })
.ToArray();
How to bind a Liststring to a DataGridView control?
Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
Then bind List<StringValue>
object to your grid. It works
How to bind nested list to datagridview in winforms
One possible solution is to “flatten” the Book
list. If we override the Books
ToString
method to output the books ID
and Name
... then we could then add a property to the Student
class that creates a single string from all the Books
in the list. Something like…
Book Class…
public class Book {
public int ID { get; set; }
public string Name { get; set; }
public override string ToString() {
return ID + " - " + Name;
}
}
Then create a new string
property ListOfBooks
in the Student Class. This will get shown in the grid. Something like...
public class Student {
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
public string ListOfBooks {
get {
return string.Join(", ", lstBk);
}
}
}
This will put all the books from the list into a single cell in the grid. If there is too much data in the cell, then I would suggest using a master-detail with two grids. One for the student and another to display the books from the “selected” student in the “student/Master” grid.
Using a Master-Detail with two grids.
Create a new winforms project, drop a couple of DataGridView
s onto the form and the code below should demonstrate one way to implement a Master-Detail using the classes you have posted.
In this case, the Book
ToString
override is obviously not needed in addition to the added ListOfBooks
property in the Student
class. They may look like the original post…
public class Book {
public int ID { get; set; }
public string Name { get; set; }
}
public class Student {
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
}
We will need some mechanism to “signal” when the user “selects” a different cell in the “Student/Master” grid. For this, we will wire up the grids SelectionChanged
event. In that event, the code "cast" the selected Student
in the grid to a Student
object, then uses the Students
lstBk
list to display into the “Book/Details” grid. This event may look something like below…
private void dataGridView1_SelectionChanged(object sender, EventArgs e) {
Student student = (Student)dataGridView1.CurrentRow.DataBoundItem;
dataGridView2.DataSource = student.lstBk;
}
When the grids are loaded, the details grid is filled using the first row in the master grid as in most cases, this is the default selected cell.
To complete this example, 10 Students
are added to the “Student/Master” grid such that each student has a random number of books between 1 and 6.
List<Student> AllStudents;
Random rand;
public Form1() {
InitializeComponent();
dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
AllStudents = new List<Student>();
rand = new Random();
}
private void Form1_Load(object sender, EventArgs e) {
for (int i = 1; i < 11; i++) {
AllStudents.Add(GetStudent(i, "Student_" + i + 1));
}
dataGridView1.DataSource = AllStudents;
dataGridView2.DataSource = AllStudents[0].lstBk;
}
private Student GetStudent(int studentID, string name) {
int numberOfBooks = rand.Next(1, 7);
int bookNumber;
List<Book> books = new List<Book>();
for (int i = 0; i < numberOfBooks; i++) {
bookNumber = rand.Next(1, 10000);
books.Add(new Book { ID = bookNumber, Name = "Book" + bookNumber });
}
return new Student { ID = studentID, Name = name, lstBk = books };
}
I hope this makes sense.
c# WinForm DataGridView bind List in List
You can use CellFormatting
event of DataGridView
to provide a friendly representation of categories
property:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//Use zero based index of the cell that contains categories
var cell= 3;
if (e.ColumnIndex == cell && e.RowIndex >= 0)
{
var categories = (List<object>)dataGridView1.Rows[e.RowIndex].Cells[cell].Value;
e.Value = string.Join(", ", categories.Select(x => x.ToString()));
}
}
In this case, categories
contains List of product categories names (string).
So selecting ToString()
is OK. But for a case of List<SomeClass>
, you either should override ToString
of SomeClass
or select one of it's properties.
As another option you can shape the result of query using a new ViewModel
or using anonymous type, but in the current situation which Product
model doesn't belong to you and it has lot's of properties, previous solution is the most simple option.
How to bind Listdynamic to datagridview in c# windows form
I know this question is old but it might help someone looking to do this.
Create a DataTable from the dynamic object and bind the DataTable to GridView
public static DataTable GetDataTableFromDynamicObject ( List<dynamic> listData )
{
DataTable table = new DataTable ( );
if ( listData.Count > 0 )
{
var firstRow = ( IEnumerable<KeyValuePair<string, JToken>> ) ( JObject ) listData.First ( );
foreach ( KeyValuePair<string, JToken> property in firstRow.OrderBy ( x => x.Key ) )
table.Columns.Add ( new DataColumn ( property.Key ) );
foreach ( var data in listData )
{
DataRow row = table.NewRow ( );
var record = ( IEnumerable<KeyValuePair<string, JToken>> ) ( JObject ) data;
foreach ( KeyValuePair<string, JToken> kvp in record )
{
row [ kvp.Key ] = kvp.Value;
}
table.Rows.Add ( row );
}
}
return table;
}
Related Topics
In Ruby, What Is the Equivalent to an Interface in C#
Upload File Through C# Using JSON Request and Restsharp
Unity: Apple Game Center iOS7 Registers the Scores for Only 30 Minutes in the Leaderboard
How to Call Code Behind Server Method from a Client Side JavaScript Function
JavaScript Date to C# via Ajax
How to Call an ASP.NET C# Method Using JavaScript
Asp.Net-Mvc: Razor '@' Symbol in Js File
How to Convert JavaScript Datetime to C# Datetime
How to Return JSON with ASP.NET & Jquery
How to Convert JavaScript Date Object to Ticks
How to Load a C# Dll in Python
Python: Inflate and Deflate Implementations
C# Version of Java's Synchronized Keyword
Why C# Implements Methods as Non-Virtual by Default