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

thb*_*hbl 2 c# wpf checkbox datagrid

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

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

<DataGrid Name="myGrid">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox Checked="CheckBox_Checked"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    <DataGridTextColumn Header="CustomerID" Width="Auto" Binding="{Binding CustomerID}"/>
    <DataGridTextColumn Header="ItemID" Width="Auto" Binding="{Binding ItemID}"/>
<DataGrid>
Run Code Online (Sandbox Code Playgroud)

C#代码:

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

运行时出错:

System.ArgumentOutOfRangeException

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

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

thb*_*hbl 8

我终于找到了!非常简单.

DataRowView drv = (DataRowView)myGrid.SelectedItem; 
String result = (drv["CustomerID"]).ToString(); 
MessageBox.Show(result);
Run Code Online (Sandbox Code Playgroud)


Gáb*_*kás 6

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>
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

您的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);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Command="{Binding CheckCommand}" CommandParameter="{Binding ElementName=myGrid, Path=SelectedItem}"
Run Code Online (Sandbox Code Playgroud)

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