.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 bound to empty (generic) collection can only add one item

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

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?



View Complete Post

More Related Resource Links

How to convert the datagrid bound column item itself link to another detail page without using hyper

Dear experts, I would like to make the datagrid bound column to redirecting to the details page . For example , when my mouse over certain row of bound column in datagrid , it will change the colour to blue . Also , I can click anywhere of the row and the will redirect to the detail page . Can any expert help me on that ? Notes : I do not want to use hyperlink column and do not want to fix the text for every row. I want to use datafield, CommandName and CommandArguement. Thanks & Rgds

WPF toolkit DataGrid does not show new row with empty collection



I have exactly the same issue present on the post: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/cdc0fb6f-2335-42e2-98d7-4bd73ffffc8c

However, the answer is still unclear to me, confusing. So I would like to clarify what do I have to get the new blank row on the datagrid.

My custom collection is called PieceUIObjects (derived from ObservableCollection) containing PieceUIObject objects.

What do I have to change in my collection in order to properly "inform" the datagrid how my object is so that the new row is added on it when the collection is initialized with no elements?

Kindly Regards,


Software Developer and AI Enthusiast. www.twitter.com/ikondrasovas

Format Generic List Bound to Gridview


I have a generic list of a custom type. The custom type has a string and double.

I'm binding the list to a gridview and it outputs everything fine.

I'm trying to format the double column into a currency format. It is in a template field as I'm calculating a running total. I pass the value to a function that returns a double and adds the current value to a running total which I will show in the footer.

The format is not changing to currency as expected when using String.Format("{0:c}", GetTotal(Convert.ToDouble(Eval("Amount"))))

Any ideas on what might be going on and how to fix this?


How to Cache System.Collection.Generic.List object


I need to cache System.Collection.Generic.List object with expiration time

var Root = from feed in feedhotel.Descendants(ota + "HotelContent")
                           where (feed.Attribute("HotelCode") != null)
                           select new xmlhotel()




return Root.ToList();

Is it possible to cache Root.ToList() for some time....

Filtering a grid column when the column is bound to a collection


My SetUp (I am using EF for my data):

1 Grid bound to a collection of Vehicle Objects

1 Combobox with multiselect enabled bound to a list of VehicleExtras.

Each vehicle has a collection of extras. 

My Problem:

What I need to do is have the Grid filter Vehicles based on whether those vehicles have the selected VehicleExtras from the Combobox

Can anyone point me in the right direction as to how this filtering should be done (if it is at all possible!)



datagrid item.ItemIndex keep selecting the wrong row number

I apologize in advance for my poor english:1. I have a dropdownList within my datagrid and its already populated fine (22 rows in my datagrid)2. The select item for the 21 row is the same as the select item of the 22 row3. When trying to do selectedIndexChange for the 22 row, it didn't seem to work. The error: Dim ddl As DropDownList = CType(sender, DropDownList)Dim dgi As DataGridItem = CType(ddl.Parent.Parent, DataGridItem)Dim rowID As Integer = dgi.ItemIndex The rowID keep staying at 20 even though the selectedIndexChanged is happening in row 22( ie. rowID should be 21)Does anyone seen this problem before??

Remove item (Cookie) from basket (Cookie Collection)

Hi I am busy building a shopping cart with cookies. I have datalist which I populate from the cookies with a delete button next to each cookie Here is the code:public partial class Basket_Checkout : System.Web.UI.Page { //List<ProductItemObject> ProductsList = new List<ProductItemObject>(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindList(); } } private void BindList() { dlstProducts.DataSource = null; dlstProducts.DataSource = ProductsList(); dlstProducts.DataBind(); } public List<ProductItemObject> ProductsList() { StringBuilder sb = new StringBuilder(); int loop1, loop2; HttpCookieCollection MyCookieColl; HttpCookie MyCookie; MyCookieColl = Request.Cookies; // Capture all cookie names into a string array. String[] arr1 = MyCookieColl.AllKeys; // Grab individual cookie objects by cookie name. List<ProductItemObject> CurrentBasket = new List<ProductItemObject>(); for (loop1 = 0; loop1 < arr1.Length; loop1++) { ProductItemObject item = new ProductItemObject(); MyCo

Binding DataGrid to empty DataTable

Hi, I'm very much new to WPF and am finding it a bit tricky to find my way in the mass of (not always great) documentation. Right now I'm struggling to get the grid to display it's UI when bound to an empty datatable. In my XAML: <DataGrid Name="grid" ItemsSource="{Binding}" />  In my code-behind (MainWindow constructor, following InitializeComponent): var dt = new DataTable(); dt.Columns.Add("col1"); dt.Columns.Add("col2"); //var r = dt.Rows.Add("toto", "tata"); grid.DataContext = dt; If I comment out the line that adds a row to the table, all is well -- the grid generates columns and displays UI. But if the table is empty, the grid renders a thin horizontal white rectangle with no column names and it doesn't seem possible to interact with this at all. As it happens, I want the grid to be empty by default, so I need to somehow get the grid to play along. If anyone knows why this happens and what to do to solve it, I'd much appreciate the help!

DataGrid bound with GetFile() - Need to use session variable in Link

 OK this is what i have. In my project i have the following folder structures. /Secure/Settlements/2507/some.pdf where the folder named 2507 corresponds with a "driverid" which is their loginid (session variable named "cid") i need to set the DataNavigateUrlStringFormat to a path which includes a session variable and i am lost, i have tried <!# <!= with no luck can someone help me get the proper format? All i want to do is list all the files in each users folder. It displays the correct files in the datagridnames in the datagrid but the link created is wrong. I need the datanavigateurlstringformat to be  "~/secure/settlements/SESSION("CID")/{0} Can i even use a session variable in the DataNavigateUrlStringFormat? Here is my code:  <%@ Page Title="" Language="VB" MasterPageFile="~/Secure/MasterPage.master" %> <%@ Import Namespace="System.IO" %> <script runat="server"> Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) If Not Page.IsPostBack Then Session("Cid") = Nothing If User.Identity.IsAuthenticated Then If User.IsInRole("Administrators") Then If Request("cid") IsNot Nothing Then Session("Cid")

How do I get an item of a collection by index?

Hello, I have a StackPanel whose children are all Expander controls. I can Add an Expander control to the StackPanel. I can Insert an Expander control into the StackPanel at specific location. I can Remove an Expander control from the StackPanel at a specific location. But, I cannot find a way to get one Expander control from the StackPanel. There is a CopyTo, but that is for copying to an array, I only need to look an one Expander control at a specific location. Since I can Insert into a specific location and Remove from a specific location, you'd think I'd be able to look at a specific location. The following does not work, where "s" is the StackPanel, p (an int) is the position, and there is an Expander control at that location: Expander x = s[p]; // [] is not allowed on collections. How do I get an item of a collection by index?  Regards, Robert Note: I work on various aspects or one or more programs, working on what is most important at the time. Some questions I ask are on aspects of the program that are not important right now or I'm using a workaround for now. I'll eventually get back to those answers received and respond. Those that are high priority get responses very soon. Thanks for your input, it is appreciated.

Restoring from Site Collection Recycle Bin - Item Added

When I restore a list item from the normal recycle bin I can access the item using properties.ListItem. However, when restoring from the Site Collection recycle bin, the listitem is null?! Ok, I thought, the SPItemEventProperties object I have also provides me with WebUrl, ListId and ListItemId so I can spin up a new SPSite with WebUrl, use openweb to get my SPWeb, use ListId to get the correct list and then the ListItemId to get the item. A bit long winded but should get me where I need to be. This would be ok, but at runtime I got an exception list not found. On investigation it seems the WebUrl property is wrong. I've run this on a few different lists/sites and it is consistently wrong! The value I'm seeing is http://[webapp]/sites/[sitecol]/sites/[sitecol]/[web]. Note the repitition of /sites/[sitecol]?! This is really frustrating and very poor. So not only is the ListItem property null(?), but there is no easy way to get the list item manually! Does anyone else see this behaviour? Sharepoint is really testing my sanity this week!    

WPF DataGrid does not show new row on empty linq query

I'm using Linq to Entities and bind a linq query to the WPF 4 DataGrid datacontext.  The linq query look something like this:                  var query = from s in this.db.Customers                         orderby s.Name                         select s;             private ContextEntities db = new ContextEntities();             private BindingListCollectionView View;             this.View = ((BindingListCollectionView)CollectionViewSource.GetDefaultView(query));             this.DataContext = this.View; If my Customers table does not have any record, the DataGrid does not show any row for user to add.  I have CanUserAddRows set to true.  I found another post that address this issue but it say to create a new entity type.  http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/cdc0fb6f-2335-42e2-98d7-4bd73ffffc8c My project

ComboBox with bound SelectedItem displays new item even if selection fails internally



I'm a WPF beginner and currently exploring some techniques and use cases. This is one of my test setups:


<Window x:Class="wpfTest.MainWindow"
    Title="MainWindow" Height="350" Width

Hide empty row in a datagrid

I am using a datagrid with a hyperlink column that opens a detail
 window using a DataGridHyperlinkColumn. 
I guess that the default datagrid always has an empty row as the 
last row. This means that there is an Edit hyperlink that is not 
associated with an ID. 
Can you either hide that row, so every row is tied to a 'real' 
datarow. Or, can you change the link on the empty row 
to be an Add link that would open the detail window as a 
'New' window? 

<Grid DataContext="{StaticResource eventsViewSource}">
    <DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" xmlns:sys="clr-namespace:System;assembly=mscorlib"  Height="200" HorizontalAlignment="Left" ItemsSource="{Binding}" Name="eventsDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="544" Margin="21,12,0,0" VerticalGridLinesBrush="LightGray">
        <sys:String x:Key="edit">Edit</sys:String>
        <DataGridHyperlinkColumn Binding="{Bin

Microsoft Matrix Framework DataGrid - Update Command - Convert empty strings to NULL



we have a AutoGenerateColumns-enabled WmxDataGrid in which we are able to update table rows in a DataBase connected with a SqlDataSource.

Each time we clear a field an empty string is written to the database where we want to write DBNull values.

At the moment we generate the update string via UPDATE... SET.. and the SQL Server function NULLIF(value, '').

Works proper but when I want to add the values to e.NewValues in BeginUpdate event I'm not able to read the values from the auto generated text boxes.

How do I do that? Is there an easier way to automatically convert empty strings to NULL values?


DataGrid - how to make Column sorting dynamic, to cater for when bound data changes?

I'm using a DataGrid in a VS2010 WPF C# project.  I have bound the DataGrid to an ObservableCollection<SummaryItem>.  When you click on a column heading it sorts the data at that point in time.

Question - How would I arrange such that the sorting in the DataGrid is dynamic, so that when data changes (within the ObservableCollection<SummaryItem>) the sorting keeps working.

Notes: Binding approach is via DataGrid

      private ObservableCollection<SummaryItem> _summaryData = new ObservableCollection<SummaryItem>();
      SummaryDataGrid.ItemsSource = _summaryData;
      SummaryDataGrid.AutoGeneratingColumn += (s, e) =>
        //if (e.Column.Header.ToString() == "ProcessName")
        //  e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
        e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
  public class SummaryItem : INotifyPropertyChanged
    public event PropertyChangedEvent

Create workflow to create list item in calendar list of a DIFFERENT site collection


I work for a school district.  Each school has a SharePoint calendar.  We set up each school as its own site collection.  I would like to create a workflow that would send their calendar events to a district calendar, which is also its own site collection.

Example,  School A enters creates a new item on their personal school calendar.  They click YES in the column called SendToDistrictCalendar.  The workflow would be triggered to create this same item in the district calendar (which is in a different site collection) when SendToDistrictCalendar is checked YES.

We're using Windows Server 2003 with Windows SharePoint Services 3.0

I am a mid-level SharePoint user.  I would appreciate ANY and ALL help to make this work!!


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