.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Datagrid Validation depending on whole collection - enforcing unique values

Posted By:      Posted Date: October 22, 2010    Points: 0   Category :WPF

I have a situation where I have an IList<T> collection of objects bound to a datagrid. I have one property, name, bound to a DataGridTextColumn. I want to enforce the rule that name should be unique within the collection and was wondering what might be the best way to do it.

Most of the validation examples I've seen either validate a single cell or else validate a row, allowing you to compare several values within the same row. But I need to validate the value of a single cell based on the values in the entire collection.

View Complete Post

More Related Resource Links

Input Validation: Enforcing Complex Business Data Rules with WPF


Windows Presentation Foundation has a rich data binding system that includes flexible support for business data validation. We take a look at implementing some complex data input validation scenarios that include customized data errors for users.

Brian Noyes

MSDN Magazine June 2010

How to pupolate one Drop Down list values dynamically depending on the value of another Drop down fr


i have two dropdowns in my Custom form.

One drop down displays all the list titles present in the current site.

i want to update another drop down with the list of columns(Field Names not the items).

i am able to get list named in one drop down but i am not able to figure out how to dynamically populate the another drop down with list of columns

any ideas

Comparing Enum values in a collection - BC42025: Access of shared member, constant member, enum mem


I am upgrading from asp1.1 to 2.0

I use collection classes to sort data (e.g in datagrids etc)


Enum newsFields
End Enum

Public Overloads Sub Sort(ByVal sortField As newsFields, ByVal isAscending As Boolean)
Select Case sortField
Case newsFields.title

DataGrid ValidationRule or IDataErrorInfo validation code called multiple times for each data change

Following my enquiry regarding a problem in Datagrid validation, for which managing exceptions is apparently a problem, I tested the two other methods: using validation rules, or implementing the IDataErrorInfo interface. I ran into other problems there, more insidious this time. This has been done on Windows7 (32-bit), .NET 4.0.30319. 1) IDataErrorInfo When this interface is implemented, the this[string columnName] property is called four times for each modification: two times before the cell enters edit mode (with the old value in the corresponding property) two times when the new value has to be validated (with the new value) It strikes me as not really efficient, is there something wrong with my code? Here's the C# part: using System; using System.Windows; using System.Collections.ObjectModel; using System.ComponentModel; namespace DataGridTest2 { public partial class MainWindow : Window { ObservableCollection<User> users; public MainWindow() { InitializeComponent(); users = new ObservableCollection<User>() { new User { Name = "Teddy", Age = "2" }, new User { Name = "Avi", Age = "19" } }; datagrid.ItemsSource = users; datagrid.Focus(); } } public class User : INotifyPropertyChanged, IDataErrorInfo { string name; public string Name

DataGrid exception on validation failure (DeferRefresh is not allowed...)

In the same series as the DataGrid validation scheme issues, I get an exception when a cell is invalid the DataContext changes This happens in a DataGrid, which is bound to a CollectionViewSource. This CVS itself has a DataContext bound to the currently selected product of a ListBox. So we are editing the details of product, those details include a data list in a DataGrid (DataGridTextColumn in this case). Either by using a data type that implements IDataErrorInfo or by using a ValidationRule, if the validation fails the DataGrid reacts by keeping the TextBox and showing a red box around it (when the validation is OK, the cell is tranformed back to a TextBlock). Nothing prevents me from selecting another product. The DataGrid then shows the new data and everything is fine. But if I come back to the product which failed validation, I get this exception: InvalidOperationException, 'DeferRefresh' is not allowed during an AddNew or EditItem transaction. How can I prevent that? What is the correct way of cancelling the edit on that faulty cell when another product is selected, or when the DataContext changes? I can detect those events, but CancelEdit() doesn't work on the DataGrid (no result). I'm using .NET 4.

Update with unique random generated values.

Hi there, I have an issue with an update of a column with unique random generated values, using SQL 2005. What I want to achieve is to create unique username for a list of let's say 1000 rows. My approach, which may be wrong, is as follows: to create a view to retrieve a random generated number of 7 digits; to use a function that retrieves the number from the view and checks if it is unique in the table or not (if it is, the number is returned, if it is not, a new one will be generated and so on); to update the table using that random generated number. The problem is that it does not work. It does not generate unique numbers, not all the times (you have to test by running the code few times). I suspect it is something with the update, but not sure how to solve it. Here are the steps to reproduce the problem. Create the table: CREATE TABLE [dbo].[TB_Temp]( [ID] [int] IDENTITY(1,1) NOT NULL, [ADM_USERNAME] [nvarchar](7) COLLATE Latin1_General_CI_AS NULL, ) ON [PRIMARY] Add some test rows: DECLARE @i INT SET @i = 0 WHILE @i <= 1000 BEGIN INSERT INTO TB_TEMP (ADM_USERNAME) VALUES ('') SET @i = @i +1 END Create the view to random generate 7 digits numbers: CREATE VIEW vw_RandNumberForAdminUserName AS SELECT ROUND((9999999 - 1000000 - 1) * RAND() + 1000000, 0) AS RandNumber Create the function to retrieve the unique 7 digits number: CREATE FUNCTION [dbo].[fn

Create unique constraint on a column which has null values

Hi All, I have a table suppose 'Temp' having one of the column as 'ColA' which has some null values as well as non null values. Now i have a requirement to create a unique constraint on it. We have tried but couldnt do it.Apart from having a trigger on insert and update statements is there any other alternate. Can any one please help me on this. Thanks & Regards, Srikanth  

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign

Using Visual Studio with MySQL.In my XSD dataset I created a query. It runs perfect. I can preview the data fine.In my BLL I wrote code (see below) to retrieve the query results and I'm getting...Using db As New dsDemoTableAdapters.DemoTableAdapter Dim dt As New DataTable dt = db.GetDemo(DemoId) ' ERROR HAPPENS HEREFailed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.Why would previewing the data work but in code it fails?Any ideas?

Unique values for a filed



My requirement is, my filed should enforce unique values.Im using MOSS 2007. how to achive this? please guide me.Thanks in advance

Selecting Unique Combinations of multiple row values



I have a table called 'Permutations' that lists every single combination of 5 numbers that could be selected from numbers 1 to 10.

(the first few rows are as follows, there are 30240 in total):


Number 1| Number 2| Number 3| Number 4| Number 5|

1 | 2 | 3 | 4 | 5

2 | 3 | 4 | 5 | 1

3 | 4 | 5 | 1 | 2

4 | 5 | 1 | 2 | 3

5 | 1 | 2 | 3 | 4

2| 3 | 4 | 5 | 6

3 | 4 | 5 | 6 | 2


and so on.


I want to write a query that only returns the unique combinations of these. So, from the rows provided above, the only rows that the query would return would be

Number 1| Number 2| Number 3| Number 4| Number 5|

1 | 2 | 3 | 4 | 5
2 | 3 | 4 | 5 | 6

Is there an easy way of doing this (note that the correct query would return 252 rows)?


Changing Datagrid Cell foreground colour depending on previous value



I have a datagrid bound to a observable collection and a background thread is regularly updating the collection when an event is fired.( subscribed to a market data service) . I need to change the foreground of the cell value if (Previousvalue > NewValue) . I guess I need a conveter but how can I get access to the previous value ? Or is there a smarter way to do this. Performace is a concern as well.

Thanks v much.


Accepting Unique Values only: I manage to do it but is there a more elegant way?


Hi everyone,

I'll try to make this concise. Anyways, I'm trying to only allow unique data to my database. my database. What I did before adding the entry is to use a Search Query for the value of the txtbox

"SELECT IDnum WHERE IDnum = '" & txtID & "'"

Then compare it with that of the txtbox.

IF objReader("IDNum") <> txtID.textbox then add the entry Else Display a Warning.

in the above code, I can detect the when the user entered an existing value. however, If the user entered a NEW (unique) value an error is Raised "Invalid attempt to read when no data is present" I hit the wall with this.

So what I did, Since I can detect Duplicates and have errors when entering unique value, I used the ON ERROR GOTO statement: I did it like this.

On Error Goto errHandler

   If objReader("IDNum") = txtID.textbox then
     lbl1.text = "Existing Record"
     Exit Sub
   End IF


  'do the codes to add the entry

  Resume exitHERE

DataGrid bound to empty (generic) collection can only add one item


Hi All,

I have a datagrid where the itemssource is bound to an typed observable collection:

ObservableCollection<ItemViewModel> Items;

Initially, the collection is empty (although not null). The datagrid shows me one row, and creates an item in the collection for me automatically. I can edit this row just fine.

However, there is no way of adding a new row. I believe this is because the grid only adds a row when I've finished editing the current one, and since there is but one row I cannot leave that row! I would like to add a fresh row as soon as the user begins editing the current one (bit like the windows forms datagridview).

How can I solve this problem?



wpf Datagrid bound to a Simple List of Long values - not so simple


Somewhere I've lost the plot.  I have a complicated senario, and solved most of it, but still I have one issue that illudes me.  Here goes

User Control has custom Dependancy Properties so that it can bind to it's host window.  One property Route is a string.  The string is actually a comma delimited list of long (BigInt stored values in SQL 2008r2 - pulled through a DataSet, then parsed into a string) ex.  "9,6,12"  Real simple so far.  The user control binds a CollectionViewSource to this string, and uses a custom converter to turn the string into a list(of long)... (or ObservableCollection(of Long), or BindingList(of Long))  The key is the value must be a long, when pulled.  Next enters the DataGrid...

I have a datagrid with 1 column.  Its a DataGridComboBoxColumn.  Its item source is bound to an actual dataset.datatable based CollectionViewSource called RoutingLocations.  A simple list of ID,Abbrev,LocationID.  I bind the DisplayValue to Abbrev.  So I get a nice lookup of the RoutingLocations in the comboBox Column.  Then my list(of Long) gets attached to the DataGrid as it's ItemSource.  End Result  I get 3 rows properly displaying the selected Abbrev for the supplied ID.

Now the problem.  I can not get this datagrid to update the source (it nev

Dynamic Sql depending on parameter values



I have only just started to use Reporting Servcies and would like to know is there any way of putting IF statments into the SQL statment depending on the value of a selected parameter.

="select  code, cid, name + '(' + code + ')' as ShopName, qty, val, salesdate  from shops" & 
" inner join sal_sumdaily on code = shopcode inner join calendar on salesdate between weekstart and weekend" &
" where trading = 0 and shopclosed = 0 and cid = " & Parameters!RP_CID.Value & "" &
" and l4l = " & Parameters!RP_L4L.Value & "" &
" and newarea = " & Parameters!RP_Area.Value & "" &
" order by code"

What I would like to do is when "Parameter!RP_Area.value" = 99 then miss that part of the sql statment out, something like this.

="select  code, cid, name + '(' + code + ')' as ShopName, qty, val, salesdate  from shops" & 
" inner join sal_sumdaily on code = shopcode inner join calendar on salesdate between weekstart and weekend" &
" where trading = 0 and shopclosed = 0 and cid = " & Parameters!RP_CID.Value & "" &
" and l4l = " & Parameters!

Deleted values are replaced automatically when user presses tab in Datagrid


I have a WPF application which is using the WPF DataGrid.It is working with  anonymous behaviour in the following scenerio.

We entered text in the horizontal cells(A1,B1,C1,D1.....)

Selected all the cells in which data is entered and clicked on delete button in the keyboard. all values are deleted.Then,selected the first cell(A1) and entered some text and clicked on tab key continuously. Then,Deleted data are showing in the cells upon pressing  tab key in the respective cells. Any solutions and suggestions  related to this are welcome.

Thanks in advance.



Dynamicobject collection binding on WPF DataGrid , not working ?



I am trying to bind dynamic list of items to the WPF DataGrid , but its not working .

my Dynamic list is

 // CustomDynamicObj is inherited from DynamicObject

  dynamic listItems = new List<CustomDynamicObj>();

 this.dataGrid1.DataContext = listItems;

And my XAML is

   <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}" Name="dataGrid1" VerticalAlignment="Stretch"  />

If I add columns through code in DataGrid then above code works fine , but I want to Autogenerate columns .

Any workaround for this plz ?



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend