从DataGrid WPF C#中的选定行获取特定单元格的数据

 烂哥居士 发布于 2023-01-12 11:49

我有一个DataGrid,我从我的SQL数据库填充数据.现在我想从我选中的行中获取一个特定的单元格(第二个单元格).

这就是我现在拥有的:WPF XAML:


    
        
            
                
                    
                
            
        
    
    

C#代码:

private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        DataGrid row = (DataGrid)myGrid.SelectedItems[1];
        System.Windows.MessageBox.Show(row);
    }

运行时出错:

System.ArgumentOutOfRangeException

{"索引超出范围.必须是非负数且小于集合的大小.\ r \nParameter name:index"}

我究竟做错了什么?我是否必须使用另一种方法来获取我想要的细胞?

2 个回答
  • MVVM模式。

    您的XAML:

    <DataGrid Name="myGrid" Grid.Row="1"  SelectionMode="Single" AutoGenerateColumns="False" CanUserAddRows="True" ItemsSource="{Binding YourCollection}" IsReadOnly="True" Background="#FFB8C1CB">
    <DataGrid.Columns>
    
            <DataGridTextColumn Header="ID" Binding="{Binding yourColumnItem}" />
    
        </DataGrid.Columns>
    </DataGrid>
    

    ViewModel:

    public ObservableCollection<YourType> YourCollection { get; private set; }
    public DelegateCommand checkCommand { get; private set; }
    
    
    public YourViewModel(){
        checkCommand = new checkCommand(param => checkExecuted(param));
    }
    
    private void CheckExecuted(Object param)
    {
            YourType item = param as YourType;
    
            YourCollection = new ObservableCollection<YourType>();
            YourCollection = model.ReadInvoices();  //you'll need a model class
            DoStuff(item.yourColumnItem);  //get the cell you want
    }
    

    App.xaml.cs

    private YourViewModel _ViewModel;
    
    public App()
    {
       _ViewModel = new YourViewModel();
    }
    
    protected override void OnStartup(StartupEventArgs e)
    {
            base.OnStartup(e);
    
            _MainWindow = new MainWindow();
            _MainWindow.DataContext = _ViewModel;
            _MainWindow.Show();
            //delete the startupuri row from App.xaml
    
    }
    

    您的DelegateCommand类:

    using System;
    using System.Windows.Input;
    
    namespace yourSolution.ViewModel
    {
    
    public class DelegateCommand : ICommand
    {
        private readonly Action<Object> _Execute; 
        private readonly Func<Object, Boolean> _CanExecute; 
    
    
        public DelegateCommand(Action<Object> execute) : this(null, execute) { }
    
    
        public DelegateCommand(Func<Object, Boolean> canExecute, Action<Object> execute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
    
            _Execute = execute;
            _CanExecute = canExecute;
        }
    
    
        public event EventHandler CanExecuteChanged;
    
    
        public Boolean CanExecute(Object parameter)
        {
            return _CanExecute == null ? true : _CanExecute(parameter);
        }
    
    
        public void Execute(Object parameter)
        {
            _Execute(parameter);
        }
    
    
        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, EventArgs.Empty);
        }
    }
    }
    

    DatabaseModel.cs:

    public ObservableCollection<YourType> ReadInvoices()
    {
            Connect();  //write connection
            YourCollection.Clear();  //this is a private data part
            MySqlCommand cmd = new MySqlCommand(write your query);
            MySqlDataReader dr = cmd.ExecuteReader();
    
            YourCollection.Clear();
            YourType item = new YourType();
    
            while (dr.Read()){
              item.column = dr.GetInt32("columnName"); //or any other type
              YourCollection.Add(item);
            }
    
            dr.Close();
            Disconnect();
    
    return YourCollection;
    }
    

    将xaml中的命令绑定到所选项目。这样,它将成为CheckCommand的参数:

    Command="{Binding CheckCommand}" CommandParameter="{Binding ElementName=myGrid, Path=SelectedItem}"
    

    我希望这能涵盖所有内容。当然,您将需要EventHandlers与App.xaml.cs进行通信,但是我不知道在处理完单元之后您想做什么。我只做了3次,希望能解决。

    2023-01-12 11:51 回答
  • 我终于找到了!非常简单.

    DataRowView drv = (DataRowView)myGrid.SelectedItem; 
    String result = (drv["CustomerID"]).ToString(); 
    MessageBox.Show(result);
    

    2023-01-12 11:51 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有