Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7041327
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T02:01:43+00:00 2026-05-28T02:01:43+00:00

I am using WPF datagrid. I am providing context menu for row-header and column-header.

  • 0

I am using WPF datagrid. I am providing context menu for row-header and column-header. The code is as mentioned below:

MainWindow.xaml

<Window x:Class="WpfApplication10.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cmd="clr-namespace:WpfApplication10"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="Insert Column Before" Command="cmd:ContextMenuCustomCommands.InsertColumnBeforeCommand" />
                        <MenuItem Header="Insert Column After" Command="cmd:ContextMenuCustomCommands.InsertColumnAfterCommand"/>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type DataGridRowHeader}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="Delete" Command="Delete"/>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <Grid.CommandBindings>
        <CommandBinding Command="cmd:ContextMenuCustomCommands.InsertColumnBeforeCommand" CanExecute="InserColumnBefore_CanExecute" Executed="InserColumnBefore_Executed"/>
        <CommandBinding Command="cmd:ContextMenuCustomCommands.InsertColumnAfterCommand" CanExecute="InsertColumnAfter_CanExecute" Executed="InsertColumnAfter_Executed"/>
    </Grid.CommandBindings>
    <DataGrid x:Name="grdEmployee" ItemsSource="{Binding}" AutoGeneratingColumn="grdEmployee_AutoGeneratingColumn" LoadingRow="grdEmployee_LoadingRow" SelectionUnit="CellOrRowHeader">

    </DataGrid>
</Grid>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;

namespace WpfApplication10
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SqlConnection empCon = null;
        private SqlCommand empCmd = null;
        private DataSet empDS = null;
        private SqlDataAdapter empAdap = null;
        private string query = "SELECT * FROM Employees";
        public MainWindow()
        {
            InitializeComponent();

            this.grdEmployee.ItemsSource = this.GetEmployeeData().DefaultView;
        }

        private DataTable GetEmployeeData()
        {
            try
            {
                empCon = new SqlConnection(Application.Current.Properties["connectionStr"].ToString());
                empCmd = new SqlCommand(query, empCon);
                empAdap = new SqlDataAdapter(empCmd);
                empDS = new DataSet();
                empAdap.Fill(empDS);
            }
            catch (SqlException sqlEx)
            {
            }
            finally
            {
                if (empCon != null)
                    empCon.Dispose();

                if (empCmd != null)
                    empCmd.Dispose();
            }

            if (empDS != null)
            {
                for (int count = 1; count <= empDS.Tables[0].Columns.Count; count++)
                {
                    empDS.Tables[0].Columns[count - 1].ColumnName = Utility.ConvertNumber(count).ToString();
                }
                return empDS.Tables[0];
            }
            else
            {
                return null;
            }
        }

        private void grdEmployee_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {

        }

        private void grdEmployee_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }

        private void InserColumnBefore_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void InserColumnBefore_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void InsertColumnAfter_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void InsertColumnAfter_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }
    }

    public class Utility
    {
        private static string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        public static string ConvertNumber(int number)
        {
            string result;
            number -= 1;
            int rest = number % 26;
            int q = number / 26;
            if (q == 0)
            {
                result = chars[rest].ToString();
            }
            else
            {
                result = ConvertNumber(q) + chars[rest];
            }
            return result;
        }
    }

    public static class ContextMenuCustomCommands
    {
        public static readonly RoutedUICommand InsertColumnBeforeCommand = new RoutedUICommand("Insert Column Before", "Insert Column Before", typeof(MainWindow));
        public static readonly RoutedUICommand InsertColumnAfterCommand = new RoutedUICommand("Insert Column After", "Insert Column After", typeof(MainWindow));
    }
}

App.xaml.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace WpfApplication10
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            string connectionStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Northwind;Data Source=(local);";
            Application.Current.Properties["connectionStr"] = connectionStr;
        }
    }
}

The problem I am facing is, The context menu on column header remain disabled until and unless I access the datagrid. I am not able to figure out the reason.

Please help me. Do let me know if you need any other info.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T02:01:44+00:00Added an answer on May 28, 2026 at 2:01 am

    As noted above the problem seemed to be stemming from the fact that the DataGrid was not focused when the click was made.

    Calling gid.Focus(); in the loaded event fixed the problem by bringing focus on the GridView.

    As for detecting the column clicked, you can likely get that through an event handler similar to getting Cell and Row information detailed in this article

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using a WPF datagrid. I am providing a context menu for row-header
How to change column header's background color when using WPF datagrid? Need to modify
I am using wpf toolkit's datagrid i want to marge a row for all
I am trying to figure out how to bind a WPF DataGrid's column header
I am using WPF DataGrid and I would like to allow the user to
I am using WPF datagrid. Data I am binding to the grid is not
I am currently using a WPF datagrid which needs to be able to load
I am using a WPF DataGrid where one of the columns has a requirement
I'm using the WPF DataGrid control to show some details and a select button,
I'm using buildin WPF DataGrid in .net 4. I can set the background of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.