Question

HowTo use a gridView in WinForms with an objectdatasource with full support of edit, add, delete??

Asked by: JLoewner

I do have a problem I am stuck with for 2 days:

1st and important: It is a winApp, not an WebApp
I am using VS2005, C# on WinXP.

I have an c# object (a class).
I want to display these objects in a gridView. It should be updateable, deleteable, ...

I have created a objectdatasource from the class.
I have created a function returning List<myClass> which reads the actual data from a database.

On load of the grid form form I assign to the gridView.Datasource my List<myClass> function value.

All values are listed correct in the gridView.

Up to here all is fine. (Maybe sorting will be missed in the future).

This is where I am stuck:
I havent found a way to delete, update, or create new records and send them back to the database.

Trying the IEditableObject interface for the dataClass didn't help really. And it is restricted to changes.

So does anybody know how to use a gridView in WinForms with an objectdatasource based on a class with full support of edit, add, delete?

Maybe a simple example source would be all I need.

This is a test project to learn howto use the objectdatasource:
So it is not urgent.

Best
Juergen

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-11-09 at 09:56:14ID22950651
Tags

objectdatasource

,

gridview

,

winforms

Topics

Microsoft Visual Studio Express

,

MS SQL Server

,

C# Programming Language

Participating Experts
2
Points
50
Comments
29

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. headers in datagridview in winforms VS2005
    In Winforms datagridview VS2005 C# How do I control the font size of the headers? I would like also a good link to handle the datagridview. I know the gridview of the ASP.NET and now I would like to learn about the datagridview in the winforms Thankyou
  2. paging in datagridview in winforms
    In winforms VS2005 C# I have a datagridview. If I have many rows in the gridview. how can I make paging in it like the gridview in asp.net? Anat
  3. tabcontrol winforms C# VS2005
    In winforms C# VS2005 using a tabControl If I press a tab how can I identify on which tabl I pressed? Thankyou anat
  4. enumerator in gridview
    In VS2005 winforms C# I have a datagridview binding to a dataset. I want to see in the gridview a new column that will be an enumerator that will show the number of the row starting from 1. I want that if I delete a row this enumerator will update. How can I implement this? T...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: TheLearnedOnePosted on 2007-11-09 at 10:06:57ID: 20251561

Here is a simple approach:

1) Drop a DataGridView on a form

2) Drop a BindingSource on a form

3) Create a Datasource for the BindingSource

4) Bind the DataGridView to the BindingSource:  DataSource + DataMember

5) Use the generated TableAdapter to fill the DataSet defined in step #3.

Bob

 

by: JLoewnerPosted on 2007-11-09 at 11:14:57ID: 20252147

Hi Bob:
1) Drop a DataGridView on a form
Done.
2) Drop a BindingSource on a form
Created by the obectdatasource
3) Create a Datasource for the BindingSource
?? The datasource is a List<class> function (Or the objectdatasource??? HOW???)
4) Bind the DataGridView to the BindingSource:  DataSource + DataMember
?? Done. Maybe its not clear what you mean with:"DataSource + DataMember" Found no datamember!
5) Use the generated TableAdapter to fill the DataSet defined in step #3.
?? The TableAdapter is never created.
This is the part which holds the update,add,insert procs WHEN using a web app (aspx form file)
This is what I miss.

What you describe is what happens when creating a web app (using aspx page with gridview).

WHAT I have done:
1) created a winform for a win app
2) created a datagridview
3) created a class with its properties which are for the gridview
4) created an objectdatasource from this class
5) the datagridview created a bindingsource from the dataobjectsource
7) I created a function which returns a list of <class> objects.
8) on winform constructor I assigned the gridview datasource the mentioned list<class> function
9) the data are listet correctly

There is NO tableadapter.
No chance for add,apdate,delete!

What have I done wrong?
What should I do to get my add, insert, delete?

Best
Juergen

 

by: TheLearnedOnePosted on 2007-11-09 at 14:21:40ID: 20253631

What I tried to describe to you was a way to create a data source easily for the DataGridView that can be accomplished through the designer.  You would get a TableAdapter, with the ability to select, insert, update, and delete data from a DataTable.  Is there a reason that you need an ObjectDataSource?  

Bob

 

by: JLoewnerPosted on 2007-11-10 at 00:13:54ID: 20254959

Hi Bob!

"...Is there a reason that you need an ObjectDataSource?..."
YES!
From my initial post: "This is a test project to learn howto use the objectdatasource"

Best
Juergen

 

by: TheLearnedOnePosted on 2007-11-10 at 04:59:19ID: 20255408

How are you using the ObjectDataSource from a WinForms application?   It is an ASP.NET control, and I didn't think that it could be used outside of that environment.

Bob

 

by: JLoewnerPosted on 2007-11-10 at 05:48:11ID: 20255541

Hi Bob,
from the datasources explorer create a new objectdatasource from a class.
The class propperties are to be used (displayed).

Drop a gridview on a winform.
From the small arrow on the upper right of the gridview (just don'tr know how it is called in english) select the objectdatasource.
This creates a myClassBindingSource
(Shortcut is to drag and drop the objectdatasource from the datasource explorer onto the  winform)

write a class list like:
    public static BindingList<myClass> getAllMyClass() {
      BindingList<myClass> list = new BindingList<myClass>();
      using(SqlConnection connection = new SqlConnection(myApp.Properties.Settings.Default.myAppConnectionString)) {
        using(SqlCommand command = new SqlCommand("[adb].getAllData, connection)) {
          command.CommandType = CommandType.StoredProcedure;
          connection.Open();
          using(SqlDataReader reader = command.ExecuteReader()) {
            while(reader.Read()) {
              WebLogon temp = new myClass(
                (string)reader["data1"],
                (string)reader["data1´2"],
                reader["data3"] is DBNull?null:(string)reader["data3"],
                (DateTime)reader["data4"],
                reader["data5"] is DBNull ? (DateTime?)null : (DateTime?)reader["data5"]
              );
              list.Add(temp);
            }
          }
          return list;
        }
      }
    }

you could also try:
 public static List<myClass> getAllMyClass() {
instead of
 public static BindingList<myClass> getAllMyClass() {
 
List<> works fine too.  

In the main form constructor:
myClassBindingSource.DataSource = BusinessObjects.getAllMyClass();

Now all data are shown in the grid.

Here I am stuck.
I still have no idea how to implement create,delete, update.

Any idea Bob?

Juergen

 

by: TheLearnedOnePosted on 2007-11-12 at 08:25:17ID: 20265079

1) >>From the small arrow on the upper right of the gridview
SmartTag

2) I don't use the wizards, so I didn't think that was possible.

3) Are you selecting from a table with a primary key set?

Bob

 

by: JLoewnerPosted on 2007-11-12 at 09:17:36ID: 20265528

Hi Bob,
ad 2) I tried it with and without the wizard: no difference in my goal of edit,delete,create

ad 3) The Table?? I handle an object, so that should not make a difference.
But YES, the example table in the background has a key set.

Any ideas how to get edit,delete,create with an objectdatasource to work?
i.e. here with a datagridview

Best
Juergen

 

by: TheLearnedOnePosted on 2007-11-13 at 05:43:18ID: 20271311

Juergen,

Have you seen this walk-through from Microsoft?

Walkthrough: Connecting to Data in Objects  
http://msdn2.microsoft.com/en-us/library/ms171892(VS.80).aspx

The article talks about creating a TableAdapter, which should help you with your CRUD functionality.

Bob

 

by: JLoewnerPosted on 2007-11-13 at 06:28:25ID: 20271635

Hello Bob,
I haven't read the article.

But a first glance shows that it does what I do so far. It just puts the List<> inside the class.
And sorting.

The rest is a walkthru meant exactly what the word means.
Not ver eficient, when a db is in the background as the factory for the class.

And it simply shows no way, when I change in a dataViewGrid a value howto intercept an edit,create,delete with something like a pointer to the regarding datarow set, so I can pick up the "key" value or something like that and all the rest for create,update,delete.

The sorting (order) shown is not of much interest, as the db in the background could easily be sortet by the "order by" statement.

The Tableadapter discussed shows how to fill the Objects. I do that handcoded.
The oblects are NOT in a DB-table!
If so there is no need of an object.
They are either assembled maybe over several tables with additional attributes for the object or pure objects.
But what about unconventional databases: simple text, xml, ...

What I still will try on your hint: Take any table table as a dummy to create a tableadapter and then use the update,create,... to intercept them and use it "my way".
A few tries didn't get me further.
But I have to stop here and as I have to do my usual work....

So where we are?
I feel still asking: How can I adapt create, edit, delete in an winapp with a datagridview to the underlying objectdatasource?

Best
Juergen

 

by: TheLearnedOnePosted on 2007-11-13 at 10:41:34ID: 20273853

Juergen,

Since you created code to build a list of classes, then it should be fairly simple to create more code for the insert, update and delete functionality.  I mentioned the TableAdapter because it looked like you were using a database, like SQL Server, with a stored procedure, to build the class list.

Bob

 

by: JLoewnerPosted on 2007-11-13 at 12:22:41ID: 20274734

Hello Bob,
at time I use a SQL DB with logon data. Simple and straightforward.

Later it will be some measurement data colllected from several sources.
They are in a Grid to inspect and change them b4 saving them to a DB.

But essentially I look for a general purpose solution ( to learn now and use it later) where I can handle the objectdatasource as a usual sq db source. The main obstacle at time is the update,edit,create.

I look for a solution how to implement a class as an object database source so I can use it no matter what kin of background data there are.

I prefer the OO access as it gives me more freedom.

But I still need to test the approach to create a dummy tableadapter for a sql DB which I than "switch" to the objectdatasurce.

Best
Juergen

 

by: TheLearnedOnePosted on 2007-11-14 at 06:07:41ID: 20279910

Juergen,

Try this:

1) Delete -- keep track of which records need to deleted from the source, and use this to remove from the list:

        myClassBindingSource.List.Remove(object)
        myClassBindingSource.List.RemoveAt(index)

2) Update -- update the values in the controls bound to myClassBindingSource.

3) Insert -- add a new 'myClass' instance to the list.

4) When you need to save the changes, loop through the binding source list, and get 'myClass' instances, and perform whatever action you need to update the datasource:

    foreach (myClass c in myClassBindingSource.List)
    {
    }

Bob

 

by: JLoewnerPosted on 2007-11-14 at 06:56:32ID: 20280351

Bob,
ur suggestion:
        myClassBindingSource.List.Remove(object)
        myClassBindingSource.List.RemoveAt(index)
lacks that NOTHING happens when I delete,edit,create on the datagrid.
So I can't pick up the index of the gridview, use it to look for a "key" value with which I could work on the object.

Best,
Juergen

 

by: TheLearnedOnePosted on 2007-11-14 at 08:24:30ID: 20281178

Ok, with the DataGridView bound to the BindingSource, disregard what I was saying before.  The DataGridView will handle adding and deleting from the underlying class list.  All you need to do is to write some code that will take the list and update the persistent storage.

Bob

 

by: dogbrainPosted on 2007-11-18 at 20:23:21ID: 20310243

Have the same problem as you did.. It seems it is the TableAdapter that we must use (http://msdn2.microsoft.com/en-us/library/bz9tthwx(VS.80).aspx). I do not see any problems if you use it together with INotifyPropertyChanged (http://msdn2.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(vs.80).aspx) for updates....

Not sure of how to delete objects and crating new ones yet (have foreign keys and stuff in the db). Any suggestions?

 

by: dogbrainPosted on 2007-11-18 at 20:34:08ID: 20310285

Ah...found the solution (http://msdn2.microsoft.com/en-us/library/ms233815(VS.80).aspx) will try it out tomorrow.. at first glans It felt like it was a lot of work....

 

by: JLoewnerPosted on 2007-11-19 at 03:18:48ID: 20311525

Hi dogbrain,
your link in the last comment mentions I can use the DBDirect methods:
"You save data back to the database by passing the values from your object to the TableAdapter's DBDirect methods.
Visual Studio creates DBDirect methods that can be executed directly against the database.."

But they refer to the Tableadapter. So I guess they mean the Web environment.

If you find a solution for winapps: make a minimalist approach and publish the source here as a comment.

My feeling is is that it is not possible.
Or better to say: It is possible only with a large amount of work. But I will not invent or write a whole new database system for a object db under winapps.

It has to be an easy or at maximum a moderate solution. And a general soulution. Not for a specific case.

I am just trying to learn how to use the objectdatasource and have given it up last saturday as it took too many personal resources.
Never the less I am still VERY interested when someone can show me a solution.

Best
Juergen

 

by: dogbrainPosted on 2007-11-19 at 03:56:29ID: 20311653

Eh did you look at the tutorial? DataSets are used by all kinds of applications (not just web) and in the dataset there are a tableadapter. The link I gave is to a windows application with step by step instructions. (I am working through it myselfe as soon as I have downloaded Northwind)

 

by: dogbrainPosted on 2007-11-19 at 04:02:52ID: 20311671

To be more clear: You wont use the DataSet.. only the TableAdapter it creates...

 

by: dogbrainPosted on 2007-11-19 at 07:07:20ID: 20312829

Ok.. now I have had some time to implement it. The key to everything besides using the TableAdapter is to use BindingList<T> as your data source....

The functions that you need to override are these:

protected override object AddNewCore()  called when a object is created. then calls insert
public override void CancelNew(int itemIndex)
protected override void InsertItem(int index, Customer item)
public override void EndNew(int itemIndex) called when something has changed (basicly after everything)
protected override void RemoveItem(int index)
protected override void SetItem(int index, Customer item) (Not sure if we need to change anything here)

So create a class that inherits BindingList<T> that holds your buissnessobjects..

Use it as a datasource... (just att it like a normal objectDataSource and then replace it in the forms load event)

Add debug breakpoints on all the above functions and see what happens when you use it in a DataGridView and a details view.

More info about BindingList<T>: http://msdn2.microsoft.com/en-us/library/ms132679(vs.80).aspx

 

by: JLoewnerPosted on 2007-11-19 at 09:11:32ID: 20313702

Hi dogbrain!
On my first vomment here:
"On load of the grid form form I assign to the gridView.Datasource my List<myClass> function value."

I used also BindingList. Mentioned: 11.10.2007 at 02:48PM CET, ID: 20255541

That didnt work.

I didnt get so far a TableAdapter for the objectdatasource.
When you write I shoud overwrite methods: On which object?
The non existing tableadapter or the datagridview?

If I have a working tableadapter on the objectdatasource I have no problem. But so far I haven't one.

Best
Juergen

 

by: dogbrainPosted on 2007-11-19 at 11:35:48ID: 20314695

Well it works for me :)

Ok.. Lets do this step by step

lets say you have a Customer table in the database. Create a dataset and add the customer to it.

Right click the Customer select add/query... create a query that suits your needs.... i used this "SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers" Choose next.. Click of fill a dataTable... in the return a dataTable I used the name GetTop5Customers


Make a class Customer (your buisness object). Make your own class Customers that inherits BindingList<Customer>...  (see the code below). This will be your controller object


Crate a form... crate a datasource (Data/Add new data souce).. Select Data/Show Data sources... drag it in the form from the data source tab.......... Add the following to the form load event:
private void Form1_Load(object sender, EventArgs e)
{
      Customers c = new Customers();
      this.customerBindingSource.DataSource = c;
}

just add debug markers to see how it behaves..

Hope this help you...

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
 
namespace ObjectBindingWalkthrough
{
	public class Customers: BindingList<Customer>
	{
 
		public Customers()
		{
			LoadCustomers();
		}
 
		
		private void LoadCustomers()
		{
 
			ObjectBindingWalkthrough.NorthwindTableAdapters.CustomersTableAdapter cta = new ObjectBindingWalkthrough.NorthwindTableAdapters.CustomersTableAdapter();
 
			Northwind.CustomersDataTable customerData =
				cta.GetTop5Customers();
			
foreach (Northwind.CustomersRow customerRow in customerData)
{
	Customer currentCustomer = new Customer();
	currentCustomer.CustomerID = customerRow.CustomerID;
	currentCustomer.CompanyName = customerRow.CompanyName;
 
	if (customerRow.IsAddressNull() == false)
	{
		currentCustomer.Address = customerRow.Address;
	}
 
	if (customerRow.IsCityNull() == false)
	{
		currentCustomer.City = customerRow.City;
	}
 
	if (customerRow.IsContactNameNull() == false)
	{
		currentCustomer.ContactName = customerRow.ContactName;
	}
 
	if (customerRow.IsContactTitleNull() == false)
	{
		currentCustomer.ContactTitle = customerRow.ContactTitle;
	}
 
	if (customerRow.IsCountryNull() == false)
	{
		currentCustomer.Country = customerRow.Country;
	}
 
	if (customerRow.IsFaxNull() == false)
	{
		currentCustomer.Fax = customerRow.Fax;
	}
 
	if (customerRow.IsPhoneNull() == false)
	{
		currentCustomer.Phone = customerRow.Phone;
	}
 
	if (customerRow.IsPostalCodeNull() == false)
	{
		currentCustomer.PostalCode = customerRow.PostalCode;
	}
 
	if (customerRow.IsRegionNull() == false)
	{
		currentCustomer.Region = customerRow.Region;
	}
 
	currentCustomer.HasBeenCreated = true;
	currentCustomer.Orders = new Orders(currentCustomer);
	//LoadOrders(currentCustomer);
	this.Add(currentCustomer);	
}
		}
 
 
 
 
		/// <summary>
		/// Called when a new item is created
		/// 
		/// Calls Insert item afterwards
		/// 
		/// Use this to Create a new object?
		/// </summary>
		/// <returns></returns>
		protected override object AddNewCore()
		{
		
			
			return base.AddNewCore();
		}
 
		public override void CancelNew(int itemIndex)
		{
			
			base.CancelNew(itemIndex);
		}
 
		/// <summary>
		/// Called when an item is inserted (can be new or old)
		/// 
		/// Use this to insert new object?
		/// </summary>
		/// <param name="index"></param>
		/// <param name="item"></param>
		protected override void InsertItem(int index, Customer item)
		{
			base.InsertItem(index, item);
		}
 
 
		/// <summary>
		/// Called when something has changed
		/// 
		/// Use this to update db
		/// </summary>
		/// <param name="itemIndex"></param>
		public override void EndNew(int itemIndex)
		{
			if (itemIndex != -1)
			{
				if (!this[itemIndex].HasBeenCreated)
				{
					this[itemIndex].createNewCustomerToDataBase();
				}
			}
			base.EndNew(itemIndex);
		}
 
		/// <summary>
		/// Removes the item
		/// 
		/// Use this to delete from database
		/// </summary>
		/// <param name="index"></param>
		protected override void RemoveItem(int index)
		{
			base.RemoveItem(index);
		}
 
		protected override void SetItem(int index, Customer item)
		{
			base.SetItem(index, item);
		}
 
		
	}
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:

Select allOpen in new window

 

by: JLoewnerPosted on 2007-11-20 at 02:53:52ID: 20318761

Hi dogbrain!

First of all: Many THANKS for your efforts.

This time it really looks good!

Deleteing is easy. RemoveItem is called one time, so it is safe just to pick up a key value from item to delete the item on a DataBase!

Creating has a good point in InsertItem. Just annoying is that on start it is called every time when the grid loads itself with values.
Any idea how to avoid this in the beginning? How to differ a loading datagrid from a real Create?

Creating calls EndNew 2 times before entering data, 3 times when leaving the new row.
EndNew is even called when no changes are made a gridline, just changing the line.

Using EndNew for an update would create a substancial overhead when writing the data out each time to a background database.

Do you have an idea how to catch changes made to row so only a dirty row would deliver data?
Or is there an easy check if the data have changed for that item?

Best
Juergen

 

by: JLoewnerPosted on 2007-11-20 at 04:50:43ID: 20319227

Hi dogbrain!
I think I resolved the issue regarding the edit:
I created an object (not database related) field IsDirty.
Then each property set got an entry like:
  if(value != _User) _isDirty = true;

EndNew got an:
        if(this[itemIndex].IsDirty) {
        ... update database/clearing IsDirty
        }

This should work with edititing.

============================================

Deleting is resolved.

============================================

Inserting and the annoying call on load in InsertItem is resolved by:
class level:
    private bool loading = false;
Then    
    in InsertItem:
    if(!loading) create new DB record

    In the constructor which loads the list/gridview:
      loading = true;
      LoadUsers();
      loading = false;

============================================

I just need to check by some examples if all cases are covered.

If you come up with better ideas: Great!
I am willing to learn everything what is better.

So far: I am going to check the solution by examples
when I have some more time.

And again a big thank you for your help.
I appreciate that you take the time and patience to help me.

I will hopefully find a chance to return this some time to the community.

All the best
Juergen

 

by: dogbrainPosted on 2007-11-20 at 16:23:44ID: 20324596

No problems, great that it worked for you.... :)

I am trying to get it to work over remoting at the moment.... not looking good...

By the way you can use the events on bindinglist instead...... Easyer to use.. You need to implement INotifyPropertyChanged in the object datasource to get the updates (if I remeber it correctly:
(http://msdn2.microsoft.com/en-us/library/ms229614(vs.80).aspx)

Do something like this:
BindingList<RentalLibrary.Administration.AUser> a = Administration.User.getActiveUsers();
a.AddingNew += new AddingNewEventHandler(a_AddingNew);
a.ListChanged += new ListChangedEventHandler(a_ListChanged);

And the functions:
void a_ListChanged(object sender, ListChangedEventArgs e)
{
      if(e.ListChangedType== ListChangedType.ItemAdded)
            //etc
}

void a_AddingNew(object sender, AddingNewEventArgs e)
{
      e.NewObject = new Administration.User(true);
}

 

by: JLoewnerPosted on 2007-11-21 at 00:57:46ID: 20326324

Hi dogbrain,

I played a bit with these events but they have a significant disadvantage in my eyes:
i.e. deleted event is called when the object is gone. So you have no "key" property to grab which you need for deletion in a database.
The RemoveItem looks to fit better as the object exists and you have an index to the object.
In my eyes the event is for cleanup a good idea not for the deletion itself.

The same with InsertItem: that is called AFTER the event. So the object event e.NewObject is null and I do not know what happens whe you create the object here (and how?). The event maybe good for some preparation b4 the actual creation of the object in InsertItem.

BTW: In ListChangedEventHandler  if(e.ListChangedType == ListChangedType.ItemChanged) is never fired!
This maybe a point of consideration for updates. But to take a closer look to the context I need to debug there.

Thanks for your hint(link on "INotifyPropertyChanged Interface".
I will take a closer look to it if that is better than my isDirty property.

I just implemented INotifyPropertyChanged and wow: the ListChangedType.ItemChanged worked!

Best
Juergen

 

by: dogbrainPosted on 2007-11-23 at 11:36:40ID: 20340371

So.. will you accept an answer?

 

by: JLoewnerPosted on 2007-11-23 at 13:11:12ID: 20340675

Sure!
And glad for your Help!

All the best
Juergen

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...