Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
I have data grid with five column such as Icon,position,name,gender,status..and i have assign the context menu on thata data grid..whenever i right click on context menu i want to display in message box selected row student name..to add value in data grid i am using data table..what shoul i do..
my code is
window1.xaml
<pre lang="xml"><Window x:Class="datagridimg.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="347" Width="457" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit">
    <Grid>
        <my:DataGrid  MouseRightButtonUp="dgData_MouseRightButtonUp" AutoGenerateColumns="False" Margin="12,12,26,105" Name="dataGrid1" >
            <my:DataGrid.ContextMenu>

                <ContextMenu>
                    <MenuItem Header="Add" Click="Ass_Game">
                    </MenuItem>
                </ContextMenu>
            </my:DataGrid.ContextMenu>
            <my:DataGrid.Columns>
                <my:DataGridTemplateColumn Header="Icon" Width="50" IsReadOnly="True" >
                    <my:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Path=ImgPath}" Width="20" Height="20"/>
                        </DataTemplate>
                    </my:DataGridTemplateColumn.CellTemplate>
                </my:DataGridTemplateColumn>
                <my:DataGridTextColumn Header="Position"  Binding="{Binding Path=PO}"   />
                <my:DataGridTextColumn Header=" Name" Binding="{Binding Path=NA}"  />
                <my:DataGridTextColumn Header="Gender" Binding="{Binding Path=GE}"  />
                <my:DataGridTextColumn Header="Status" Binding="{Binding Path=ST}"  />
                <my:DataGridTextColumn Header="Machine" Binding="{Binding Path=MA}"  />
            </my:DataGrid.Columns>
        </my:DataGrid>
        <Image HorizontalAlignment="Left" Margin="50,0,0,39" Name="image1" Stretch="Fill" Width="49" Height="42" VerticalAlignment="Bottom" Source="/datagridimg;component/image/offline.png" />
    </Grid>
</Window

>



window1.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;

namespace datagridimg
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        DataTable dt;
        public Window1()
        {
            InitializeComponent();
           
            dt = new DataTable();
            dt.Columns.Add("PO");
            dt.Columns.Add("NA");
            dt.Columns.Add("GE");
            dt.Columns.Add("ST");
            dt.Columns.Add("MA");
            dt.Columns.Add("ImgPath", typeof(BitmapImage));

            DataRow dr = dt.NewRow();
            dr[0] = "5";
            dr[1] = "SAM";
            dr[2] = "Male";
            dr[3] = "Offline";
            dr[4] = "Online";
            dr[5] = new BitmapImage(new Uri("/datagridimg;component/image/offline.png", UriKind.RelativeOrAbsolute));
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "3";
            dr[1] = "RAM";
            dr[2] = "Male";
            dr[3] = "Offline";
            dr[4] = "Online";
            dr[5] = new BitmapImage(new Uri("/datagridimg;component/image/offline.png", UriKind.RelativeOrAbsolute));
            dt.Rows.Add(dr);


           
            dataGrid1.ItemsSource = dt.DefaultView;
        }
        private void dgData_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            ContextMenu cxMenu = new ContextMenu();


        }
        private void Ass_Game(object sender, RoutedEventArgs e)
        {
           
           MessageBox.Show("Name of Student???????");
         
  
        }


           
        }//context menu

    }
}
Posted
Updated 1-Jun-11 21:00pm
v2

When you bind the DataGrid to the DataTable you need to set the DataGrid's SelectedValuePath to the Name column like this

C#
dr[5] = new BitmapImage(new Uri("/datagridimg;component/image/offline.png", UriKind.RelativeOrAbsolute));
           dt.Rows.Add(dr);
           dataGrid1.ItemsSource = dt.DefaultView;
           dataGrid1.SelectedValuePath = "NA";
       }

Then you can just reference the SelectedValue from the ContextMenu like this

C#
private void Ass_Game(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(dataGrid1.SelectedValue.ToString());
        }


Be aware that if your DataGrid's SelectionMode is set to Extended then this will return the Name of the first selected row. If the SelectionMode is set to single, it obviously will return only the selected row's name.

Hope this helps
 
Share this answer
 
Hi.

I can propose this solution:

1. Move context menu to the DataGrid Resources and put relativesource binding.
2. Assign context menu to the DataGridRow using DataGrid.ItemContainerStyle.
3. Change Ass_Game handler accordingly.
4. Remove dgData_MouseRightButtonUp event handler

See xaml example below:

XML
<my:DataGrid  AutoGenerateColumns="False" Margin="12,12,26,105" Name="dataGrid1" >
        <my:DataGrid.Resources>
            <ContextMenu x:Key="contextMenu">
                <MenuItem Header="Add" Click="Ass_Game"
                          Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Item}">
                </MenuItem>
            </ContextMenu>
        </my:DataGrid.Resources>
        <my:DataGrid.Columns>
            <my:DataGridTemplateColumn Header="Icon" Width="50" IsReadOnly="True" >
                <my:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="{Binding Path=ImgPath}" Width="20" Height="20"/>
                    </DataTemplate>
                </my:DataGridTemplateColumn.CellTemplate>
            </my:DataGridTemplateColumn>
            <my:DataGridTextColumn Header="Position"  Binding="{Binding Path=PO}"   />
            <my:DataGridTextColumn Header=" Name" Binding="{Binding Path=NA}"  />
            <my:DataGridTextColumn Header="Gender" Binding="{Binding Path=GE}"  />
            <my:DataGridTextColumn Header="Status" Binding="{Binding Path=ST}"  />
            <my:DataGridTextColumn Header="Machine" Binding="{Binding Path=MA}"  />
        </my:DataGrid.Columns>
        <my:DataGrid.ItemContainerStyle>
            <Style>
                <Setter Property="my:DataGridRow.ContextMenu" Value="{StaticResource ResourceKey=contextMenu}"></Setter>
            </Style>
        </my:DataGrid.ItemContainerStyle>
    </my:DataGrid>



Ass_Game Handler example:

private void Ass_Game(object sender, RoutedEventArgs e)
{
   MenuItem item = sender as MenuItem;
   if (item == null)
   {
     return;
   }

   DataRowView view = item.Tag as DataRowView;
   if (view == null)
   {
     return;
   }

   MessageBox.Show(view["NA"].ToString());
}


Have fun!!
 
Share this answer
 
v4
Comments
vishal_h 2-Jun-11 6:18am    
Sir but it every time giving me same name..on every right click..why..please help me..
Marrakech 2-Jun-11 6:27am    
Sorry mix binding expression. Please see improved solution.
vishal_h 2-Jun-11 6:29am    
OK sir...thank you..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900