简体   繁体   中英

how to access cell in datagrid? (wpf, c#)

I'm trying to get value of datagrid cell when it's clicked. how to get value of each datagrid cell when it's clicked?

For example I want to get value of Name variable (in User class) cell is clicked

please help me i've been struggling for a months...

I made a wpf application that can display datagrid contents corresponding to treeview items by clicking on them.

I want to know how to get the value of each cell when clicking a cell in the datagrid.

There is no code in the xaml datagrid of my code, so I don't know what to do.

<UserControl x:Class="VSIXProject4.ToolWindow1Control"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0"
         Background="{DynamicResource {x:Static vsshell:VsBrushes.WindowKey}}"
         Foreground="{DynamicResource {x:Static vsshell:VsBrushes.WindowTextKey}}"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300"
         Name="MyToolWindow">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Grid>
        <TreeView>
            <TreeViewItem Header="TEST1">
                <TreeViewItem Header="TEST1_ITEM"
                              MouseDoubleClick="TEST1_CLICKED"></TreeViewItem>
            </TreeViewItem>
            <TreeViewItem Header="TEST2">
                <TreeViewItem Header="TEST2_ITEM"
                              MouseDoubleClick="TEST2_CLICKED"></TreeViewItem>
            </TreeViewItem>
            <TreeViewItem Header="TEST3">
                <TreeViewItem Header="TTEST3_ITEM"
                              MouseDoubleClick="TEST3_CLICKED"></TreeViewItem>
            </TreeViewItem>
        </TreeView>

    </Grid>

    <Grid Grid.Column="1">
        <DataGrid x:Name ="Test_grid" >
            
        </DataGrid>
    </Grid>

</Grid>
**namespace VSIXProject4
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    /// Interaction logic for ToolWindow1Control.
    /// </summary>
    public partial class ToolWindow1Control : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ToolWindow1Control"/> class.
        /// </summary>
        public ToolWindow1Control()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Handles click on the button by displaying a message box.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event args.</param>
        [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Justification = "Sample code")]
        [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Default event handler naming pattern")]
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(
                string.Format(System.Globalization.CultureInfo.CurrentUICulture, "Invoked '{0}'", this.ToString()),
                "ToolWindow1");
        }

        private void TEST1_CLICKED(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            List<User> users = new List<User>();

            users.Add(new User() { Id = 1, Name = "A1", Birthday = new DateTime(1971, 7, 23) });

            users.Add(new User() { Id = 2, Name = "A2", Birthday = new DateTime(1974, 1, 17) });

            users.Add(new User() { Id = 3, Name = "A3", Birthday = new DateTime(1991, 9, 2) });

            Test_grid.ItemsSource = users;
        }

        public class User

        {

            public int Id { get; set; }

            public string Name { get; set; }

            public DateTime Birthday { get; set; }

        }

        public class User2

        {

            public int var_1 { get; set; }

            public string var_2 { get; set; }

            public string var_3 { get; set; }

        }

        private void TEST2_CLICKED(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            List<User2> users2 = new List<User2>();

            users2.Add(new User2() { var_1 = 1, var_2 = "A1", var_3 = "hi" });

            users2.Add(new User2() { var_1 = 2, var_2 = "A2", var_3 = "hello" });

            users2.Add(new User2() { var_1 = 3, var_2 = "A3", var_3 = "world" });

            Test_grid.ItemsSource = users2;
        }

        private void TEST3_CLICKED(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            List<User3> users3 = new List<User3>();

            users3.Add(new User3() { var_4 = 2341, var_5 = "aa", var_6 = "testtest" });

            users3.Add(new User3() { var_4 = 223, var_5 = "A2asd", var_6 = "helaaaalo" });

            users3.Add(new User3() { var_4 = 322, var_5 = "A3ff", var_6 = "worlfsddd" });

            Test_grid.ItemsSource = users3;
        }


        public class User3

        {

            public int var_4 { get; set; }

            public string var_5 { get; set; }

            public string var_6 { get; set; }

        }
    }


}

To get notified when the selected cells change, subscribe to the SelectedCellsChanged Event of the Datagrid.

Setting the SelectionUnit="Cell" and the SelectionMode="Single" property on the Datagrid ensures that a user can only select one cell at a time.

To get the Name property from a User you could do the following:

    private void Test_grid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        IList<DataGridCellInfo> dataGridCells = Test_grid.SelectedCells; //Holds all currently selected cells.
        DataGridCellInfo selectedCell = dataGridCells.FirstOrDefault(); //Gets the first cell in that list.
        object item = selectedCell.Item; //Gets the Item object from the cell. 

        //Here we are using pattern matching to see if 'item' is a User object. 
        if (item is User user)
        {
            string username = user.Name; //Gets the Name property from the user property
            //Do something with the name here!
        }
    }

Go here to learn more about the is keyword.

Note: The DataGridCellInfo.Item will always return the entire object and not just the property that is 'bound' to it. That's why I'm testing if Item is a User and not a string!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM