Casting Linq to IEnumerable <Datarow> - c#

I'm creating winForm app,In that Onbutton click i gather Data Tables from of Two database Mysql and Sqlite database.
I getting Casting error while on casting Linq query to IEnumerable to make fetch query values to DataTable to make display in DataGrid view.
private void button1_Click(object sender, EventArgs e)
{
var obj = new table1TableAdapter(); //Mysql Table Adapter
var obj2 = new Table1TableAdapter(); // Sqlite Table Adapter
var ds = new DataSet();
ds.Tables.Add(obj.GetData());
ds.Tables.Add(obj2.GetData());
var tab1 = ds.Tables[0];
var tab2 = ds.Tables[1];
var query = from o in tab1.AsEnumerable()
join od in tab2.AsEnumerable()
on o.Field<string>("Name") equals od.Field<string>("Name")
select new
{
Name = o.Field<string>("Name"),
Rollno = od.Field<Int64>("rollno"),
Book = o.Field<string>("Book")
};
var q2 = (IEnumerable<DataRow>)query; //Unable to cast object of type <JoinIterator>
DataTable orderTable = q2.CopyToDataTable();
dataGridView1.DataSource = orderTable;
}

Looking at your code, I'd say, why cast it to IEnumerable<DataRow> at all ? Just simply bind the query to your GridView.
dataGridView1.DataSource = query.ToList();

That's because the query object you are returning has no relation to DataRow. query is going to be an IEnumerable<SomeAnonymousType>. How is it expected to convert to DataRow?
You would need to alter your statement to make a DataRow:
select new DataRow(/* Whatever Params */) { /* More Params */ };
Then it's natively an IEnumerable<DataRow> and needs no casting.

Since your query is creating an IEnumerable you wouldn't be able to cast it to a DataRow. I also wouldn't not advise using select new DataRow(/* Whatever Params /) { / More Params */ }; since this would not be a true DataRow object and would be bad practice.
I would handle it this way. Even if this is a small project, there shouldn't be that much code in your Button_Click handler.
First, create a container object, call it a DTO or ViewModel. I suggest the later.
public class BookViewModel
{
public string Name { get; set; }
public Int64 Rollno { get; set; }
public string Book { get; set; }
}
Next, create a new class that will do your SQL queries. This will separate your Data Access logic from your form logic.
public class BookService
{
public IList<BookViewModel> GetBookViewModel()
{
var obj = new table1TableAdapter(); //Mysql Table Adapter
var obj2 = new Table1TableAdapter(); // Sqlite Table Adapter
var ds = new DataSet();
ds.Tables.Add(obj.GetData());
ds.Tables.Add(obj2.GetData());
var tab1 = ds.Tables[0];
var tab2 = ds.Tables[1];
var query = from o in tab1.AsEnumerable()
join od in tab2.AsEnumerable()
on o.Field<string>("Name") equals od.Field<string>("Name")
select new BookViewModel
{
Name = o.Field<string>("Name"),
Rollno = od.Field<Int64>("rollno"),
Book = o.Field<string>("Book")
};
return query.ToList();
}
}
Last, bind the List to your display.
private void button1_Click(object sender, EventArgs e)
{
BookService bookService = new BookService();
dataGridView1.DataSource = bookService.GetBookViewModel();
}
Now when you go back to make changes to your code, you will easily be able to modify your display logic and with out having to read through all of your intermixed code.
Example:
private void button1_Click(object sender, EventArgs e)
{
BookService bookService = new BookService();
IList<BookViewModel> books = bookService.GetBookViewModel();
if (books.Count == 0)
{
Label1.Text = "Sorry no books were found";
}
dataGridView1.DataSource = books;
}

For one thing, you're not going to be able to cast to an IEnumerable because you're query itself is not producing DataRows
select new
{
Name = o.Field<string>("Name"),
Rollno = od.Field<Int64>("rollno"),
Book = o.Field<string>("Book")
};
is creating an anonymous type.
You would have to change this to a DataRow somehow first, and then convert it to an IEnumerable.

I'm using the following statement and this works for me
UC070_WizardStepFilesDataSet.AllDossierDetailResultsRow[] searchrows =
(from a in _wizardStepPreviewDataSet.AllDossierDetailResults
where a.WingsSetNbr == row.WingsSetNbr && !a.BookCode.StartsWith("V")
select a).ToArray<UC070_WizardStepFilesDataSet.AllDossierDetailResultsRow>();

Related

How to use CopyToDataTable() method in LINQ successfully using below example only?

I have been trying something with LINQ to get all the data from a table customers in a data table. I have used SQL to LINQ class here.
SampleDataContext sdc = new SampleDataContext();
DataTable Cust = new DataTable();
// var query = from c in sdc.customers
// select c;
var query = (IEnumerable<DataRow>)sdc.customers.Select(c => c);
Cust = query.CopyToDataTable();
Console.WriteLine(Cust);
Now when I run this, I get an exception:
Unable to cast object of type 'System.Data.Linq.DataQuery1[BasicLearning.customer]' to type 'System.Collections.Generic.IEnumerable1[System.Data.DataRow]'
Why am I getting this exception?
ANS - from my understanding, which may be wrong, the (IEnumerable<DataRow>) casting in above logic won't work because the result set is not an IEnumerable but IQueryable. But I am not sure if I understand this exception correctly.
So, here I am stuck now, on how to get this code running. I want to use CopyToDataTable() method. But Casting is not working.
It would be great if anyone could help me understand what I am doing wrong here and how to correct it.
as #Svyatoslav Danyliv mention you need to convert object to table. there is an extention which dynamically convert object to datatable.
void Main()
{
DataTable Cust = new DataTable();
//var query = from c in sdc.customers
// select c;
var query = Customers.Select(c => c).ConvertClassToDataTable<Customer>().AsEnumerable();
Cust = query.CopyToDataTable();
Console.WriteLine(Cust);
}
public static class Extensions
{
public static DataTable ConvertClassToDataTable<T>(this IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}

Querying in Entity Framework for fill combobox of foreign key

I have a ComboBox of provinces :
public Form1()
{
InitializeComponent();
using (AbEntities c = new AbEntities())
{
comboBox1.DataSource = c.tbl_Province.ToList();
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Province";
}
}
Now I want to list cities for each province in another combobox.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString() != null)
{
int pvc = Convert.ToInt32(comboBox1.SelectedValue.ToString());
string sqlString = "SELECT ID,City FROM tbl_City Where ProvinceID = pvc"
using (AbEntities c = new AbEntities())
{
comboBox2.DataSource = c.tbl_City.ToList();
comboBox2.ValueMember = "ID";
comboBox2.DisplayMember = "City";
}
}
}
I wrote the following query. But cities are not filtered
I don't see any filtering in your code. May be you should apply some like this:
comboBox2.DataSource = c.tbl_City.Where(x=>x.ProvinceID == pvc).ToList();
Explanation:
The loose SQL-query string in your code has no application. Since your post is tagged with entity-framework I assume that AbEntities is a DataContext.
In this case tbl_City implements the IQueryable interface and allows you to call Where directly in your code. In this example I used the method syntax.
The ToList() call will execute the query and materialize the results.
This can also be accomplished using the query syntax:
comboBox2.DataSource = (from x in c.tbl_City
where x.ProvinceID == pvc
select x).ToList();
You need to query your DbSet, e.g.:
c.tbl_City.Where(c => c.ProvinceID == pvc).ToList();
Further:
there is no relation between the SQL statement and the filter.
You might want to read something about linq,
And here is more about EF: http://www.entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx

Simplify my C# Linq statement?

class :
class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
List
List<Foo> lst = new List<Foo>();
Datatable :
DataTable dt = GetFromDb ()....
I want to fill lst with records from dt.
I've managed doing :
Array.ForEach(dt.AsEnumerable().ToArray(), y = > lst.Add(new Foo()
{
Id = int.Parse(y["id"].ToString()), Name = y["name"].ToString()
}));
question :
Can't I do something else like dt.AsEnumerable().Select(_ => fill lst ) ?
I know that part of the select signature (in this case ) is Func<datarow,void> which wont compile
But still , is there any other way of doing this besides the ugly way of mine ?
Using LINQ to DataSet:
var foos = from row in dt.AsEnumerable()
select new Foo()
{
Id = row.Field<int>("id"),
Name = row.Field<string>("name")
};
// create a new list
List<Foo> lst = foos.ToList();
// update: add items to an exisiting list
fooList.AddRange(foos);
Try this
var fooList = (from t in dt.AsEnumerable()
select new Foo { Id = t.Field<int>("Id"),
Name= t.Field<string>("Name") }).ToList();
The AsEnumerable extension method on a DataTable will return a Collection of DataRows. then you do a projection from your Linq Result with required fields. Since it is dataRow type, you need to specify what each column type will be.
You are on the right track, you can do the following:
lst = dt.AsEnumerable().Select(y = > new Foo()
{
Id = Convert.ToInt32(y["id"]), Name = y["name"] as string
}).ToList();
EDIT: To add to an existing list
I would normally just concatenate two lists:
lst = lst.Concat(dt.AsEnumerable().Select(...)).ToList();
However having seen ken2k's answer, I think I will now start using AddRange instead.
You could do:
List<Foo> lst = dt.AsEnumerable().Select(z => new Foo
{
Id = int.Parse(z["id"].ToString()),
Name = z["name"].ToString()
}).ToList();
EDIT:
If you want to append to an existing List<Foo> instance:
lst.AddRange(dt.AsEnumerable().Select(z => new Foo
{
Id = int.Parse(z["id"].ToString()),
Name = z["name"].ToString()
}));
I got another solution via Rows property :
List<Foo> results = (from DataRow myRow in dt.Rows
select new Foo()
{
Id =int.Parse( row["id"].ToString()),
Name = row["name"].ToString()
}).ToList();

A Problem in DataGridView : datagridview seems readonly to user (WinForms)

I have a datagridview in my form. It fills by selecting country with cities of country.I have set the property (AllowUsersToAddRow = True)
but when i run my project user can't add or edit or delete any row.I checked it.It is not readonly(readonly = false) and It is enable (Enabled = true)
What's the problem?
Code of fill datagridview:
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex>=0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
dgvValues.DataSource = from record in Program.dal.Cities(CountryId) select new { record.City};
}
If you find this question useful don't forgot to vote it.
To give a simplified example, if I do the equivalent of your query, such as:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
dataGridView.DataSource = cities;
I get the same result as you - no option to add new rows, but if I change to BindingList<T> and set this to AllowNew it all works:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
var citiesBinding = new BindingList<City>(cities);
citiesBinding.AllowNew = true;
dataGridView.DataSource = citiesBinding;
EDIT - with a solution for your particular example:
private class City
{
public string Name { get; set; }
}
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex >= 0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
var queryResults = from record in Program.dal.Cities(CountryId) select new City { Name = record.City };
var queryBinding = new BindingList<City>(queryResults.ToList());
queryBinding.AllowNew = true;
dgvValues.DataSource = queryBinding;
}
Note that a) I had to change the anonymous type in the query select into a concrete type City and also change the IEnumerable<T> returned by Linq query to an IList<T> compatible type to create the BindingList<T>. This should work, however :)

How to enable DataGridView sorting when user clicks on the column header?

I have a datagridview on my form and I populate it with this:
dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
.OrderBy(s => s.Apellidos)
.ToList();
Now, I use the s.Apellidos as the default sort, but I'd also like to allow users to sort when clicking on the column header.
This sort will not modify the data in any way, it's just a client side bonus to allow for easier searching for information when scanning the screen with their eyes.
Thanks for the suggestions.
Set all the column's (which can be sortable by users) SortMode property to Automatic
dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
.OrderBy(s => s.Apellidos)
.ToList();
foreach(DataGridViewColumn column in dataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
Edit: As your datagridview is bound with a linq query, it will not be sorted. So please go through this [404 dead link, see next section] which explains how to create a sortable binding list and to then feed it as datasource to datagridview.
Code as recovered from dead link
Link from above is 404-dead. I recovered the code from the Internet Wayback Machine archive of the page.
public Form1()
{
InitializeComponent();
SortableBindingList<person> persons = new SortableBindingList<person>();
persons.Add(new Person(1, "timvw", new DateTime(1980, 04, 30)));
persons.Add(new Person(2, "John Doe", DateTime.Now));
this.dataGridView1.AutoGenerateColumns = false;
this.ColumnId.DataPropertyName = "Id";
this.ColumnName.DataPropertyName = "Name";
this.ColumnBirthday.DataPropertyName = "Birthday";
this.dataGridView1.DataSource = persons;
}
As Niraj suggested, use a SortableBindingList. I've used this very successfully with the DataGridView.
Here's a link to the updated code I used - Presenting the SortableBindingList - Take Two - archive
Just add the two source files to your project, and you'll be in business.
Source is in SortableBindingList.zip - 404 dead link
One more way to do this is using "System.Linq.Dynamic" library. You can get this library from Nuget. No need of any custom implementations or sortable List :)
using System.Linq.Dynamic;
private bool sortAscending = false;
private void dataGridView_ColumnHeaderMouseClick ( object sender, DataGridViewCellMouseEventArgs e )
{
if ( sortAscending )
dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).ToList ( );
else
dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).Reverse ( ).ToList ( );
sortAscending = !sortAscending;
}
You don't need to create a binding datasource. If you want to apply sorting for all of your columns, here is a more generic solution of mine;
private int _previousIndex;
private bool _sortDirection;
private void gridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == _previousIndex)
_sortDirection ^= true; // toggle direction
gridView.DataSource = SortData(
(List<MainGridViewModel>)gridReview.DataSource, gridReview.Columns[e.ColumnIndex].Name, _sortDirection);
_previousIndex = e.ColumnIndex;
}
public List<MainGridViewModel> SortData(List<MainGridViewModel> list, string column, bool ascending)
{
return ascending ?
list.OrderBy(_ => _.GetType().GetProperty(column).GetValue(_)).ToList() :
list.OrderByDescending(_ => _.GetType().GetProperty(column).GetValue(_)).ToList();
}
Make sure you subscribe your data grid to the event ColumnHeaderMouseClick. When the user clicks on the column it will sort by descending. If the same column header is clicked again, sorting will be applied by ascending.
your data grid needs to be bound to a sortable list in the first place.
Create this event handler:
void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
//Add this as an event on DataBindingComplete
DataGridView dataGridView = sender as DataGridView;
if (dataGridView == null)
{
var ex = new InvalidOperationException("This event is for a DataGridView type senders only.");
ex.Data.Add("Sender type", sender.GetType().Name);
throw ex;
}
foreach (DataGridViewColumn column in dataGridView.Columns)
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
And initialize the event of each of your datragrids like this:
dataGridView1.DataBindingComplete += MakeColumnsSortable_DataBindingComplete;
You can use DataGridViewColoumnHeaderMouseClick event like this :
Private string order = String.Empty;
private void dgvDepartment_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (order == "d")
{
order = "a";
dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth }) .OrderBy(s => s.Apellidos).ToList();
}
else
{
order = "d";
dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth }.OrderByDescending(s => s.Apellidos) .ToList()
}
}
there is quite simply solution when using Entity Framework (version 6 in this case). I'm not sure but it seems to ObservableCollectionExtensions.ToBindingList<T> method returns implementation of sortable binding list. I haven't found source code to confirm this supposition but object returning from this method works with DataGridView very well especially when sorting columns by clicking on its headers.
The code is very simply and relies only on .net and entity framework classes:
using System.Data.Entity;
IEnumerable<Item> items = MethodCreatingItems();
var observableItems = new System.Collections.ObjectModel.ObservableCollection<Item>(items);
System.ComponentModel.BindingList<Item> source = observableItems.ToBindingList();
MyDataGridView.DataSource = source;
put this line in your windows form (on load or better in a public method like "binddata" ):
//
// bind the data and make the grid sortable
//
this.datagridview1.MakeSortable( myenumerablecollection );
Put this code in a file called DataGridViewExtensions.cs (or similar)
// MakeSortable extension.
// this will make any enumerable collection sortable on a datagrid view.
//
// BEGIN MAKESORTABLE - Mark A. Lloyd
//
// Enables sort on all cols of a DatagridView
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
public static class DataGridViewExtensions
{
public static void MakeSortable<T>(
this DataGridView dataGridView,
IEnumerable<T> dataSource,
SortOrder defaultSort = SortOrder.Ascending,
SortOrder initialSort = SortOrder.None)
{
var sortProviderDictionary = new Dictionary<int, Func<SortOrder, IEnumerable<T>>>();
var previousSortOrderDictionary = new Dictionary<int, SortOrder>();
var itemType = typeof(T);
dataGridView.DataSource = dataSource;
foreach (DataGridViewColumn c in dataGridView.Columns)
{
object Provider(T info) => itemType.GetProperty(c.Name)?.GetValue(info);
sortProviderDictionary[c.Index] = so => so != defaultSort ?
dataSource.OrderByDescending<T, object>(Provider) :
dataSource.OrderBy<T,object>(Provider);
previousSortOrderDictionary[c.Index] = initialSort;
}
async Task DoSort(int index)
{
switch (previousSortOrderDictionary[index])
{
case SortOrder.Ascending:
previousSortOrderDictionary[index] = SortOrder.Descending;
break;
case SortOrder.None:
case SortOrder.Descending:
previousSortOrderDictionary[index] = SortOrder.Ascending;
break;
default:
throw new ArgumentOutOfRangeException();
}
IEnumerable<T> sorted = null;
dataGridView.Cursor = Cursors.WaitCursor;
dataGridView.Enabled = false;
await Task.Run(() => sorted = sortProviderDictionary[index](previousSortOrderDictionary[index]).ToList());
dataGridView.DataSource = sorted;
dataGridView.Enabled = true;
dataGridView.Cursor = Cursors.Default;
}
dataGridView.ColumnHeaderMouseClick+= (object sender, DataGridViewCellMouseEventArgs e) => DoSort(index: e.ColumnIndex);
}
}
KISS : Keep it simple, stupid
Way A:
Implement an own SortableBindingList class when like to use DataBinding and sorting.
Way B:
Use a List<string> sorting works also but does not work with DataBinding.
I suggest using a DataTable.DefaultView as a DataSource. Then the line below.
foreach (DataGridViewColumn column in gridview.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
After that the gridview itself will manage sorting(Ascending or Descending is supported.)
If you get an error message like
An unhandled exception of type 'System.NullReferenceException'
occurred in System.Windows.Forms.dll
if you work with SortableBindingList, your code probably uses some loops over DataGridView rows and also try to access the empty last row! (BindingSource = null)
If you don't need to allow the user to add new rows directly in the DataGridView this line of code easily solve the issue:
InitializeComponent();
m_dataGridView.AllowUserToAddRows = false; // after components initialized
...
Create a class which contains all properties you need, and populate them in the constructor
class Student
{
int _StudentId;
public int StudentId {get;}
string _Name;
public string Name {get;}
...
public Student(int studentId, string name ...)
{ _StudentId = studentId; _Name = name; ... }
}
Create an IComparer < Student > class, to be able to sort
class StudentSorter : IComparer<Student>
{
public enum SField {StudentId, Name ... }
SField _sField; SortOrder _sortOrder;
public StudentSorder(SField field, SortOrder order)
{ _sField = field; _sortOrder = order;}
public int Compare(Student x, Student y)
{
if (_SortOrder == SortOrder.Descending)
{
Student tmp = x;
x = y;
y = tmp;
}
if (x == null || y == null)
return 0;
int result = 0;
switch (_sField)
{
case SField.StudentId:
result = x.StudentId.CompareTo(y.StudentId);
break;
case SField.Name:
result = x.Name.CompareTo(y.Name);
break;
...
}
return result;
}
}
Within the form containing the datagrid add
ListDictionary sortOrderLD = new ListDictionary(); //if less than 10 columns
private SortOrder SetOrderDirection(string column)
{
if (sortOrderLD.Contains(column))
{
sortOrderLD[column] = (SortOrder)sortOrderLD[column] == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
}
else
{
sortOrderLD.Add(column, SortOrder.Ascending);
}
return (SortOrder)sortOrderLD[column];
}
Within datagridview_ColumnHeaderMouseClick event handler do something like this
private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
StudentSorter sorter = null;
string column = dGV.Columns[e.ColumnIndex].DataPropertyName; //Use column name if you set it
if (column == "StudentId")
{
sorter = new StudentSorter(StudentSorter.SField.StudentId, SetOrderDirection(column));
}
else if (column == "Name")
{
sorter = new StudentSorter(StudentSorter.SField.Name, SetOrderDirection(column));
}
...
List<Student> lstFD = datagridview.DataSource as List<Student>;
lstFD.Sort(sorter);
datagridview.DataSource = lstFD;
datagridview.Refresh();
}
Hope this helps
Just in case somebody still looks for it, I did it on VS 2008 C#.
On the Event ColumnHeaderMouseClick, add a databinding for the gridview, and send the order by field like a parameter. You can get the clicked field as follows:
dgView.Columns[e.ColumnIndex].Name
In my case the header's names are similar to view field names.
I have a BindingList<> object bind as a data source to dataGridView.
BindingList x1;
x1 = new BindingList<sourceObject>();
BindingSource bsx1 = new BindingSource();
bsx1.DataSource = x1;
dataGridView1.DataSource = bsx1;
When I clicked the column header, no sorting takes place.
I used the SortableBindingList answer provided by Tom Bushell.
Having included two source files into my project
SortableBindingList.cs
PropertyComparer.cs
Then this change is made to my code:
Be.Timvw.Framework.ComponentModel.SortableBindingList x1; // 1
x1 = new Be.Timvw.Framework.ComponentModel.SortableBindingList<sourceObject>(); // 2
BindingSource bsx1 = new BindingSource();
bsx1.DataSource = x1;
dataGridView1.DataSource = bsx1;
After these changes I performed a build on my program. I am now able to sort by clicking the column headers. Only two lines need changing, they are highlighted in the code snippet above by trailing comments.
In my case, the problem was that I had set my DataSource as an object, which is why it didn't get sorted. After changing from object to a DataTable it workd well without any code complement.
If using a DataTable: dgv.DataSource = (DataTable)table
You can automatically enable Sorting for objects that contain the IComparable Interface. After creating the DataTable, when adding the columns be sure to set the type also to at least object:
table.Columns.Add("ColumnName", typeof(object))
Otherwise, if you do Not specifically give it a type, it converts the object to a string.
I spent a fair amount of time creating a dgv_ColumnHeaderMouseClick() event because it was Not sorting the DataGridView correctly, then to find that all you need to do is specify the type for the column name, and it sorts properly. And the reason it was not sorting correctly previously was because without specifying the type for DataTable columns, it will convert objects to strings.
Just instead of passing a list to the datagrid, you store the search result as a datatable.
dataGridView1.DataSource = students
.Select(s => new {
ID = s.StudentId,
RUDE = s.RUDE,
Nombre = s.Name,
Apellidos = s.LastNameFather + " " + s.LastNameMother,
Nacido = s.DateOfBirth })
.OrderBy(s => s.Apellidos)
.ToDataTable();

Categories

Resources