1
votes

My code using winforms is:

ctxTripStops = new DatabaseContextx();
ctxTripStops.TripStops.Where(p => p.TripId == id).Load();
bsTripStops.DataSource = ctxTripStops.TripStops.Local;
dgvSecondary.DataSource = bsTripStops;

I also have a bindingnavigator bound to the Datagridview. Everything works OK- add, delete and edit in the grid updates the database on SaveChanges(). What doesn't work is clicking on a column header to sort the grid. I know that you use ToBindingList() then it will sort but then I loose the add and delete functionallity. Is it possible to add the sorting capability?

1
did you set the property to allow sorting..?MethodMan
If you mean the SortMode in each column, then yes. As I said, it sorts OK if I add a ToBindingList() to the query.T. Morgan
personally I would bind the data to a DataTable and the sorting is handled for youMethodMan
Why do you think using ToBindingList() will loose the add/delete functionality? In fact ToBindingList is specifically provided to be used for WF data binding.Ivan Stoev
bsTripStops.DataSource = ctxTripStops.TripStops.Local.ToBindingList(); should do. The returned BindingList<T> implementation will stay in sync with DbSet<T>.Local property.Ivan Stoev

1 Answers

0
votes

If you are storing data locally use a data set. Drag and drop a dataset to the winform, then select untyped. If you already have data inside the gridview you can easily add that data by :

DataSet DataSet1 = new dataset

dataset1.Tables.Add("Main");

foreach(DataGridViewColumn col in GridView.Columns)
{
    string name = col.Name.ToString();
    DataSet1.Tables["Main"].Columns.Add(name);
    DataSet1.AcceptChanges();
}

foreach(DataGridViewRow row in GridView.Rows)
{
    string value1 = row.Cells[0].Value.ToString();
    string value2 = row.Cells[1].Value.ToString();
    DataSet1.Tables["Main"].Rows.Add(value1,value2);
    DataSet1.AcceptChanges();

}

To save the dataset use this code:

string path = "path to where to save";
DataSet1.WriteXml(path,XmlWriteOption.WriteScheme);

to read dataset into program

string path = "path of saved xml";
Dataset1.ReadXml(path);

//Binds with DataGrid
DataGridView1.DataSource = DataSet1;
DataGridView1.DataMember = "Main";
DataGridView1.Update();

in order to for adding a new row manually you will need to make a RowsAdded Event if your using visual studio in properties click the lighting bolt and scroll down to RowsAdded and double click it.

DataGridView1_RowsAdded_Event(object sender, EventArgs e)
{
    DataSet1.AcceptChanges();
}

you will do the same with Rows Deleted. By calling DataSet1.AcceptChanges()
you are telling the program to keep current changes.