.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

Binding DataGrid to empty DataTable

Posted By:      Posted Date: September 08, 2010    Points: 0   Category :WPF
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!

View Complete Post

More Related Resource Links

WPF 4 DataGrid (Binding to DataTable), where store new value of user edit fields? DataGrid architect


I looking for good artical about the DataGrid architecture, logical & visual.

I try to understand whre datagrid store the new value of cell, when user edit row in DataGrid. I realize that DataGrid not hold Copy of data. instead it Hold pointer to DataRow. But DataRow got new value only after user end the line Edit.

the code like:

DirectCast(DataGrid1.CurrentCell.Item, System.Data.DataRowView).Item(1) 

return the DataRow, not the new value during line Edit.

My question

1. Where DataGrid Hold the new value?

2. How access to Visual Element of each cell, like TextBlock inside the cell from Code?

Data Binding a DataGrid to a list fetch the same data multiple times

Hi, I'm using DataGrid to show data through data binding. My data are provided in a list. The setup I have is the following: DataGrid "binded" to the default view of my list that implement IList<T> and IList interfaces (MyList<T> : IList<T>, IList, INotifyCollectionChanged)             CollectionViewSource.GetDefaultView(_myList);             // Set the data context             DataContext = view; T: is here my 'business object' that hold the data, called 'MyRow'. Then the columns of the DataGrid are bound to public properties of 'MyRow' object. MyRow class has a public property of type 'object' (public object data[int index]) and first column of datagrid is bound to myRow.data[0], second column is bound to myRow.data[1] and so on.   When the datagrid is displayed, databinding kick in and my data are showed in the control. The issue I'm having is that data fetching is very repetitive even for the same rows. For example for a datagrid with 20 visible rows, the first row is fetched multiple times even if the datagrid is not resized or moved. I put break point inside my list (MyList<T> into This[T] property (public T this[int index]) and i got multiple hits into the property for the same index. Fetc

Binding DataTable data to ObjectDataSource

Hi all, I am trying to bind a DataTable into a ObjectDataSource. This ObjectDataSource data will be used to bind into my LocalReport in ReportViewer. I have already successfully binded my data into the DataTable. My problem now is how do i bind the data in my DataTable into the ObjectDataSource so that it can be used in my report? Here is my current codes: ASPX:<rsweb:ReportViewer ID="ReportViewer1" runat="server"> <LocalReport ReportPath="Modules\Report.rdlc"> <DataSources> <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="DataSet1" /> </DataSources> </LocalReport> </rsweb:ReportViewer> <asp:ObjectDataSource runat="server" ID="ObjectDataSource1"> </asp:ObjectDataSource> VB:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim dtable As DataTable = SetReportDataSource() If dtable.Rows.Count > 0 Then Dim rds As New ReportDataSource() ReportViewer1.LocalReport.DataSources.Clear() ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("Data

How can i do TwoWay Binding between listbox and datatable

I've bound my listbox to a datatable using the following code: Me.TasksListBox.DataContext = dt The datatemplate in the listbox is a collection of controls like textboxes and comboboxes, each of which is bound to a column in the datatable. The data loads fine in the listbox. As the users modify the data in the listbox by modifying combo boxes , textboxes of items in the listbox , i want the changes to propogate to datatable dt so i can save the values in the database. I am unable to figure out how this can be done. Thanks  

TwoWay Binding Datagrid To WCF Service?

Hello, i tried to bind a DataGrid in TwoWay Mode to a WCF Service. The Data get displayed but changes in DataGrid dont affect the Database, from which the WCF Service is getting the data.   I hope someone can help me... Thank you.     My Szenario: I have a WCF Service which offers exactly one Function which return a custom class. The custom class inherits from INotifyPropertyChanged and has only one DataMember, an ObservableList with my DB Entitys. //Service.svc.cs static testdatenEntities _context = null; private static testdatenEntities Get_context() { if (_context == null) { _context = new testdatenEntities(); } return _context; } public customData GetDataFromADO() { var _context = Get_context(); var result = (from lief in _context.LIEF_INFO.AsQueryable() orderby lief.LNR select lief).Skip(50).Take(50); ObservableCollection<LIEF_INFO> _ocol = new ObservableCollection<LIEF_INFO>(result); customData customdata = new customData() { List = _ocol }; return customdata; } //IService.cs [DataContract] public class customData : INotifyPropertyChanged { ObservableCollection<LIEF_INFO> _ocol = new ObservableCollection<LIEF_INFO>(); [DataMember] public ObservableCollection<LIEF_INFO> List {

Binding DataGrid RowDetailTemplate Using MVVM

In this post I will show you how you can bind the RowDetailTemplate of the data grid using the MVVM pattern. Below are the image of the sample code here you can see the default page in Image 1 and when user click on any of the record then detail of the record is shown in the RowDetailTemplate which also consist of the data grid control which you can see in the Image 2.

Click.CommandParameter null when binding on Button inside DataGrid DataGridTemplateColumn

I am having trouble getting a Click.CommandParameter to pass through with a bound Click.Command. I have a DataGrid with a DataGridTemplateColumn that contains a couple of Buttons. Using a suggestion found on the forum (http://social.msdn.microsoft.com/Forums/en/wpf/thread/541024a9-3d7e-4c6a-b88e-9a7eb7ee83a9), I was able to get the Click.Command to bind to the right command, but when arriving in the corresponding method in my ViewModel, the parameter is null.  Here is my xaml for my DataGridTemplateColumn <data:DataGridTemplateColumn Header="Case">  <data:DataGridTemplateColumn.CellTemplate>   <DataTemplate >    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">     <Button Content="Open" Margin="6,0" command:Click.Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type data:DataGrid}}, Path=DataContext.OpenCaseCommand}" CommandParameter="{Binding}"  />     <Path Data="M1,1 L1,2" Stroke="#FFCCCCCC"/>     <Button Content="Rename" />    </StackPanel>   </DataTemplate>  </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> I used Snoop to see what was going on. Everything

Binding a computed value to datagrid column

Hi, I have a WPF Datagrid with tree colums (A, B,C) which are bound to an Observable collection. The value of C is C=A+B. The value of A and B are updated via an event that I have subscribed to ( a realtime data feed). What is the best way to update the value of C each and every time A or B get chaged ? I'm new to WPF and should I use a converter to achive this ? Thanks V

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

Adding new rows to Datagrid with a Combobox column generate "two-way binding requires path or xpath"



    I have datagrid control with a template combobox column like:

 <DataGridTemplateColumn Header="Fault code" Width="75">
                                    <TextBlock Text="{Binding FaultCode1}" />

Dynamically Assign Datagrid Column Binding from XAML


I am trying to build a generic user control that will serve as a quick list maintenance screen.

I have a base ViewModel that has two string properties IDColumnName and DisplayColumnName and then a collection of objects to be edited.  Inherited view models will be created for each object type that needs to be maintained.  The usercontrols datacontext is set to the viewmodel.

What I want to do is have the datagrid, who's itemssource is bound to the collection of objects in the viewmodel, have one column and have that one column bound to the property specified in the DisplayColumnName property of the viewmodel, and I'd like to do it all in XAML.  I've got the datagrids rowdetailstemplate being dynamically determined based on the object type but am struggling with dynamically setting which property the one column displays.

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

I need help please : how do i bind dataGrid to dataTable Programmatically ?


Hi all,


please i need to know if i could  bind dataGrid to dataTable Programmatically using wpf V.S 2010 (without using Xaml code)???


i google it before but i saw solution using (DataSet) and this not useful for me because its huge application.

Note : data source is MySql.


Thanks a lot .


Abed Salem

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?


Binding Datatable to listview in Xaml



  Can any one give me solution for below code.  I know how to bind the datatable to listview in code behind, but  i don't know, how to bind it through XAML. This is my sample code. Please any one help me.

<Window x:Class="ListViewDemo.MainWindow"
Title="MainWindow" Height="350" Width="525">
<DataTemplate x:Key="checkBox">
<CheckBox IsChecked="{Binding Path=Check, Mode=TwoWay}"/>
<ListView Name="lvProcess">
<GridViewColumn Header="Dep_Type" DisplayMemberBinding="{Binding Path=Dep_Type}"/>
<GridViewColumn Header="Check" DisplayMemberBinding="{Binding Path=Check}"/>
<GridViewColumn Header="Depend

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?



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