EzDevInfo.com

datagrid interview questions

Top datagrid frequently asked interview questions

WPF datagrid empty row at bottom

I bind my datagrid using

//fill datagrid
public DataTable GameData
{
    get
    {
        DataSet ds = new DataSet();
        FileStream fs = new FileStream(IMDB.WebPage.Class.Config.XMLPath,
        FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(fs, Encoding.Default);
        ds.ReadXml(reader);
        fs.Close();
        DataTable temp = ds.Tables[0];
        return ds.Tables[0];
     }
 }

For some reason I get an empty row at the bottom. And sometimes after clicking on some buttons and checkboxes in the grid, more empty rows are added.

Why is this? And how do I block this?


Source: (StackOverflow)

Get selected row item in DataGrid WPF

I have a DataGrid, bound to Database table, I need to get the content of selected row in DataGrid, for example, I want to show in MessageBox content of selected row.

Example of DataGrid:

enter image description here

So if I select the second row, my MessageBox has to show something like: 646 Jim Biology.

Thanks.


Source: (StackOverflow)

Advertisements

JavaScript data grid for millions of rows [closed]

I need to present a large number of rows of data (ie. millions of rows) to the user in a grid using JavaScript.

The user shouldn't see pages or view only finite amounts of data at a time.

Rather, it should appear that all of the data are available.

Instead of downloading the data all at once, small chunks are downloaded as the user comes to them (ie. by scrolling through the grid).

The rows will not be edited through this front end, so read-only grids are acceptable.

What data grids, written in JavaScript, exist for this kind of seamless paging?


Source: (StackOverflow)

What is the "pressed the delete key" event for the WPF Datagrid?

I want to enable the user to highlight a row on the WPF DataGrid and press delete key to delete the row.

  • the functionality is already built into the UI of the grid, so to the user, the row disappears
  • I currently handle this on the SelectionChanged event (code below)
  • I loop through all the "e.RemovedItems" and delete them with LINQ

Problem is: even when you simply select a row and move off of it, selection change is fired and that row is in e.RemovedItems (which is odd, why would simply selecting something put it in a RemovedItems container?).

So I am looking for a DeleteKeyPressed event so I can simply handle it. What is that event called?

I am using the March 2009 toolkit.

XAML:

<Grid DockPanel.Dock="Bottom">
    <toolkit:DataGrid x:Name="TheDataGrid" 
                      SelectionChanged="TheDataGrid_SelectionChanged"
                      AutoGenerateColumns="True"
                      RowEditEnding="TheDataGrid_RowEditEnding"/>

code-behind:

private void TheDataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.RemovedItems.Count > 0)
    {
        Message.Text = "The following were removed: ";
        foreach (object obj in e.RemovedItems)
        {
            Customer customer = obj as Customer;
            Message.Text += customer.ContactName + ",";
            _db.Order_Details.DeleteAllOnSubmit(
                customer.Orders.SelectMany(o => o.Order_Details));
            _db.Orders.DeleteAllOnSubmit(customer.Orders);
            _db.Customers.DeleteOnSubmit(customer);
        } 
    }

    try
    {
        _db.SubmitChanges();
    }
    catch (Exception ex)
    {
        Message.Text = ex.Message;
    }
}


ANSWER:

Thanks lnferis, that was exactly what I was looking for, here is my finished delete handling event for the datagrid, note the KeyDown event doesn't fire for some reason.

XAML:

<toolkit:DataGrid x:Name="TheDataGrid" 
                  KeyDown="TheDataGrid_KeyDown"
                  PreviewKeyDown="TheDataGrid_PreviewKeyDown"
                  AutoGenerateColumns="True"
                  RowEditEnding="TheDataGrid_RowEditEnding"/>

code-behind

private void TheDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        var grid = (DataGrid)sender;

        if (grid.SelectedItems.Count > 0)
        {
            string checkMessage = "The following will be removed: ";

            foreach (var row in grid.SelectedItems)
            {
                Customer customer = row as Customer;
                checkMessage += customer.ContactName + ",";
            }
            checkMessage = Regex.Replace(checkMessage, ",$", "");

            var result = MessageBox.Show(checkMessage, "Delete", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                foreach (var row in grid.SelectedItems)
                {
                    Customer customer = row as Customer;
                    _db.Order_Details.DeleteAllOnSubmit(
                        customer.Orders.SelectMany(o => o.Order_Details));
                    _db.Orders.DeleteAllOnSubmit(customer.Orders);
                    _db.Customers.DeleteOnSubmit(customer);
                }
                _db.SubmitChanges();
            }
            else
            {
                foreach (var row in grid.SelectedItems)
                {
                    Customer customer = row as Customer;
                    LoadData();
                    _db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, customer); //TODO: this doesn't refresh the datagrid like the other instance in this code
                }
            }
        }
    }
}

private void TheDataGrid_KeyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("never gets here for some reason");
}

Source: (StackOverflow)

Need to format dates in dynamically built WPF DataGrid

We are binding an unknown result set to a WPF DataGrid at run time. Some of our columns are going to contain DateTime values and we need to properly format these date time fields. Without knowing which columns are going to be DateTime fields at design time, how are we able to format the columns at runtime?

We are using a DataTable's DefaultView to bind to the WPF DataGrid.


Source: (StackOverflow)

How can I disable editing cells in a WPF Datagrid?

I'm constructing a datagrid in Windows Presentation Foundation, and I have a problem. When a user double-clicks on a cell in my datagrid, the cell goes into edit mode. I want to prevent that. Instead I want users to be able to select the full row - not edit values in it.

How can I make it so that double-clicks select the full row instead of putting the clicked-on cell in edit mode?


Source: (StackOverflow)

programatically add column & rows to WPF Datagrid

I'm new to WPF. I just want to know how should we add columns and rows programatically to a DataGrid in WPF. The way we used to do it in windows forms. create table columns and rows, and bind it to DataGrid.

I believe WPF DataGrid is bit different the one used in ASP.net and Windows form (correct me if I am wrong).

I have No. of rows and columns which I need to draw in DataGrid so that user can edit the data in the cells. Let me know if you have any ideas.


Source: (StackOverflow)

WPF DataGrid - Button in a column, getting the row from which it came on the Click event handler

I've set the itemsource of my WPF Datagrid to a List of Objects returned from my DAL. I've also added an extra column which contains a button, the xaml is below.

<toolkit:DataGridTemplateColumn  MinWidth="100" Header="View">
    <toolkit:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="Button_Click">View Details</Button>
        </DataTemplate>
    </toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>

This renders fine. However on the Button_Click method, is there any way I can get the row on the datagrid where the button resides? More specifically, one of the properties of my objects is "Id", and I'd like to be able to pass this into the constructor of another form in the event handler.

private void Button_Click(object sender, RoutedEventArgs e)
    {
        //I need to know which row this button is on so I can retrieve the "id"  
    }

Perhaps I need something extra in my xaml, or maybe I'm going about this in a roundabout way? Any help/advice appreciated.


Source: (StackOverflow)

How can I set the color of a selected row in DataGrid

This seems like a no-brainer but i just can't see how to do it.

The default background color of a selected row in DataGrid is so dark that I can't read it. Is there anyway of overriding it?

Tried this (modified from Neverminds link)

<dg:DataGrid.RowStyle>
    <Style TargetType="{x:Type dg:DataGridRow}">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True" >
                <Setter Property="Background" Value="Gainsboro" />
            </Trigger>
        </Style.Triggers>
    </Style>
</dg:DataGrid.RowStyle>

But still nothing...


Source: (StackOverflow)

How do I bind a WPF DataGrid to a variable number of columns?

My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used to apply formatting. A simplified version of the output might be something like:

class Data
{
    IList<ColumnDescription> ColumnDescriptions { get; set; }
    string[][] Rows { get; set; }
}

This class is set as the DataContext on a WPF DataGrid but I actually create the columns programmatically:

for (int i = 0; i < data.ColumnDescriptions.Count; i++)
{
    dataGrid.Columns.Add(new DataGridTextColumn
    {
        Header = data.ColumnDescriptions[i].Name,
        Binding = new Binding(string.Format("[{0}]", i))
    });
}

Is there any way to replace this code with data bindings in the XAML file instead?


Source: (StackOverflow)

WPF Error: Cannot find governing FrameworkElement for target element

I've got a datagrid with a Row that has an image. This image is bound with a trigger to a certain state. When the state changes I want to change the image.

The Template itself is set on the HeaderStyle of a DataGridTemplateColumn. This template has some bindings. The first binding Day shows what day it is and the State changes the image with a trigger.

These properties are set in a ViewModel.

Properties:

public class HeaderItem
{
    public string Day { get; set; }
    public ValidationStatus State { get; set; }
}

this.HeaderItems = new ObservableCollection<HeaderItem>();
        for (int i = 1; i < 15; i++)
        {
            this.HeaderItems.Add(new HeaderItem()
            {
                Day = i.ToString(),
                State = ValidationStatus.Nieuw,
            });
        }

Datagrid:

<DataGrid x:Name="PersoneelsPrestatiesDataGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
              AutoGenerateColumns="False" SelectionMode="Single" ItemsSource="{Binding CaregiverPerformances}" FrozenColumnCount="1" >

    <DataGridTemplateColumn HeaderStyle="{StaticResource headerCenterAlignment}" Header="{Binding HeaderItems[1]}" Width="50">

                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <TextBox Text="{ Binding Performances[1].Duration,Converter={StaticResource timeSpanConverter},Mode=TwoWay}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock TextAlignment="Center" Text="{ Binding Performances[1].Duration,Converter={StaticResource timeSpanConverter}}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn> </DataGrid>

Datagrid HeaderStyleTemplate:

  <Style x:Key="headerCenterAlignment"
          TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition />
                            <RowDefinition />
                        </Grid.RowDefinitions>

                        <TextBlock Grid.Row="0" Text="{Binding Day}" />
                        <Image x:Name="imageValidation" Grid.Row="1" Width="16" Height="16" Source="{StaticResource imgBevestigd}" />
                    </Grid>

                    <ControlTemplate.Triggers>
                        <MultiDataTrigger >
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding State}" Value="Nieuw"/>                                 
                            </MultiDataTrigger.Conditions>
                            <Setter TargetName="imageValidation" Property="Source" Value="{StaticResource imgGeenStatus}"/>
                        </MultiDataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Now when I startup the project the images doesn't show and I get this error:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=HeaderItems[0]; DataItem=null; target element is 'DataGridTemplateColumn' (HashCode=26950454); target property is 'Header' (type 'Object')

Any idea why this error is showing? Thanx in advance


Source: (StackOverflow)

Change DataGrid cell colour based on values

I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml

Style TargetType="DataGridCell"

but instead of selecting a cell only is selecting all row? What am I missing?


Source: (StackOverflow)

RealWorld HazelCast

Does anyone have any real world experience with Hazelcast distributed data grid and execution product? How has it worked for you? It has an astonishingly simple API and functionality that seems almost to good to be true for such a simple to use tool. I have done some very simple apps and it seems to work as advertised so far. So here I am looking for the real world 'reality check'. Thank you.


Source: (StackOverflow)

WPF DataGrid selected row style

I'm stuck with one very stupid problem - need to style selected row in WPF DataGrid.

I want to show a rectangle with blue border instead of just filling entire row with some color.

Any ideas how to implement this? It just must be some way to make it pretty easy.


Source: (StackOverflow)

OpenClipboard Failed when copy pasting data from wpf DataGrid

I've got a WPF app using datagrid. The app worked fine until I installed VS2012 and Blend+SketchFlow preview. Now, when I'm trying to copy the data from the grid into the clipboard with ctrl+C (in any app), I'm getting following exception:

System.Runtime.InteropServices.COMException (0x800401D0): OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN))
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode, IntPtr errorInfo)
   at System.Windows.Clipboard.Flush()
   at System.Windows.Clipboard.CriticalSetDataObject(Object data, Boolean copy)
   at System.Windows.Controls.DataGrid.OnExecutedCopy(ExecutedRoutedEventArgs args)
   at System.Windows.Controls.DataGrid.OnExecutedCopy(Object target, ExecutedRoutedEventArgs args)
   at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)
   at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
   at System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter, IInputElement target, Boolean userInitiated)
   at System.Windows.Input.CommandManager.TranslateInput(IInputElement targetElement, InputEventArgs inputEventArgs)
   at System.Windows.UIElement.OnKeyDownThunk(Object sender, KeyEventArgs e)
   at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey)
   at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled)
   at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers)
   at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
   at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
   at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()

This is really annoying.

I've seen some references to this problem here and on various locations on the web, with no real solution.

I can verify that the clipboard is locked when this exception is raised in visual studio, as I couldn't copy paste the message (had to write it to a file). Also, the clipboard wasn't locked before the copy process started.

Had anybody here have this problem and solved it?


Source: (StackOverflow)