2013-10-07 196 views

答えて

12

MSDNのDataGrid Classページを参照してください。そのページから:デフォルトでは

選択、行全体は、ユーザーがDataGrid内のセルをクリックしたときに選択され、ユーザが複数の行を選択することができます。 SelectionModeプロパティを設定して、ユーザーがセル、行全体、またはその両方を選択できるかどうかを指定できます。 SelectionUnitプロパティを設定して、複数の行またはセルを選択できるか、単一の行またはセルのみを選択できるかを指定します。

SelectedCellsプロパティから選択したセルに関する情報を取得できます。 SelectedCellsChangedイベントのSelectedCellsChangedEventArgsで、選択が変更されたセルに関する情報を取得できます。 SelectAllCellsメソッドまたはUnselectAllCellsメソッドを呼び出して、すべてのセルをプログラムで選択または選択解除します。詳細については、DataGridコントロールのデフォルトのキーボードとマウスの動作を参照してください。

私はあなたに関連するプロパティへのリンクを追加しましたが、今は時間がかかりませんので、リンクをたどって解決策を得ることができれば幸いです。

+0

の延長だし、それは素晴らしいですしかし、ここでそれを見つけてください。 – OmegaMan

+1

私からの議論はありません。 – Sheridan

8

一つだけのセルを選択している場合は、ここでは、この

var cellInfo = dataGrid1.SelectedCells[0]; 

var content = cellInfo.Column.GetCellContent(cellInfo.Item); 

などの選択したセルのコンテンツを取得するコンテンツは、あなたの選択したセルが

を評価され、あなたが複数のセルを選択している場合、あなたは次のようにそれを行うことができますこの

var cellInfos = dataGrid1.SelectedCells; 

var list1 = new List<string>(); 

foreach (DataGridCellInfo cellInfo in cellInfos) 
{ 
    if (cellInfo.IsValid) 
    { 
     //GetCellContent returns FrameworkElement 
     var content= cellInfo.Column.GetCellContent(cellInfo.Item); 

     //Need to add the extra lines of code below to get desired output 

     //get the datacontext from FrameworkElement and typecast to DataRowView 
     var row = (DataRowView)content.DataContext; 

     //ItemArray returns an object array with single element 
     object[] obj = row.Row.ItemArray; 

     //store the obj array in a list or Arraylist for later use 
     list1.Add(obj[0].ToString()); 
    } 
} 
+0

単一セルのソリューションにマイナーな追加を行うと、内容は以下のようにTextblockに変更する必要があります。var content =(cellInfo.Column.GetCellContent(cellInfo.Item))TextBlock。 –

12

私はこの問題に直面したとき、私はこのようにそれに近づい:、私はDataRowViewを作成し 列INDをつかんexは、その後、使用されたもので、行のItemArray

DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem; 
int index = dataGrid1.CurrentCell.Column.DisplayIndex; 
string cellValue = dataRow.Row.ItemArray[index].ToString(); 
+2

これは、 'SelectionUnit'が' DataGridSelectionUnit.FullRow'に設定されている場合にのみ有効です。 –

+0

@Bahman_Aries 'SelectionUnit'が' Cell'のときの私の答えを見てください。 –

+0

ありがとう、私の大きな問題を解決したジョン! – DumpsterDiver

1

これらのこの試みる

/// <summary> 
    /// Take a value from a the selected row of a DataGrid 
    /// ATTENTION : The column's index is absolute : if the DataGrid is reorganized by the user, 
    /// the index must change 
    /// </summary> 
    /// <param name="dGrid">The DataGrid where we take the value</param> 
    /// <param name="columnIndex">The value's line index</param> 
    /// <returns>The value contained in the selected line or an empty string if nothing is selected</returns> 
    public static string getDataGridValueAt(DataGrid dGrid, int columnIndex) 
    { 
     if (dGrid.SelectedItem == null) 
      return ""; 
     string str = dGrid.SelectedItem.ToString(); // Take the selected line 
     str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Delete useless characters 
     if (columnIndex < 0 || columnIndex >= str.Split(',').Length) // case where the index can't be used 
      return ""; 
     str = str.Split(',')[columnIndex].Trim(); 
     str = str.Split('=')[1].Trim(); 
     return str; 
    } 

    /// <summary> 
    /// Take a value from a the selected row of a DataGrid 
    /// </summary> 
    /// <param name="dGrid">The DataGrid where we take the value.</param> 
    /// <param name="columnName">The column's name of the searched value. Be careful, the parameter must be the same as the shown on the dataGrid</param> 
    /// <returns>The value contained in the selected line or an empty string if nothing is selected or if the column doesn't exist</returns> 
    public static string getDataGridValueAt(DataGrid dGrid, string columnName) 
    { 
     if (dGrid.SelectedItem == null) 
      return ""; 
     for (int i = 0; i < columnName.Length; i++) 
      if (columnName.ElementAt(i) == '_') 
      { 
       columnName = columnName.Insert(i, "_"); 
       i++; 
      } 
     string str = dGrid.SelectedItem.ToString(); // Get the selected Line 
     str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Remove useless characters 
     for (int i = 0; i < str.Split(',').Length; i++) 
      if (str.Split(',')[i].Trim().Split('=')[0].Trim() == columnName) // Check if the searched column exists in the dataGrid. 
       return str.Split(',')[i].Trim().Split('=')[1].Trim(); 
     return str; 
    } 
4

SelectionUnit="Cell"場合は、選択した行から値を取得するために使用することができます2つの方法です:

string cellValue = GetSelectedCellValue(); 
は、

ここで:

public string GetSelectedCellValue() 
    { 
     DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0]; 
     if (cellInfo == null) return null; 

     DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn; 
     if (column == null) return null; 

     FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item }; 
     BindingOperations.SetBinding(element, TagProperty, column.Binding); 

     return element.Tag.ToString(); 
    } 

それは複雑、私が知っている...

を編集することをすべきではないように思える:これはDataGridTemplateColumn型の列に動作するようには思えません。あなたの行がカスタムクラスから構成されている場合にも、これを試みることができる、あなたはソートメンバーパスを割り当てた:

public string GetSelectedCellValue() 
    { 
     DataGridCellInfo cells = MyDataGrid.SelectedCells[0]; 

     YourRowClass item = cells.Item as YourRowClass; 
     string columnName = cells.Column.SortMemberPath; 

     if (item == null || columnName == null) return null; 

     object result = item.GetType().GetProperty(columnName).GetValue(item, null); 

     if (result == null) return null; 

     return result.ToString(); 
    } 
1

私は長い間、この1と格闘しました! (VB.NETの使用)基本的には、選択したセルの行インデックスと列インデックスを取得し、それを使用して値にアクセスします。

Private Sub LineListDataGrid_SelectedCellsChanged(sender As Object, e As SelectedCellsChangedEventArgs) Handles LineListDataGrid.SelectedCellsChanged 

    Dim colInd As Integer = LineListDataGrid.CurrentCell.Column.DisplayIndex 

    Dim rowInd As Integer = LineListDataGrid.Items.IndexOf(LineListDataGrid.CurrentItem) 

    Dim item As String 

    Try 
     item = LLDB.LineList.Rows(rowInd)(colInd) 
    Catch 
     Exit Sub 
    End Try 

End Sub 

エンドクラス

1
//Xaml Code 
<DataGrid.Columns> 
<DataGridTextColumn Binding="{Binding Path=Date, Converter={StaticResource dateconverter}, Mode=OneWay}" Header="Date" Width="100"/> 
<DataGridTextColumn Binding="{Binding Path=Prescription}" Header="Prescription" Width="900"/> 
</DataGrid.Columns> 

//C# Code 
DataRowView row = (DataRowView)grid1.SelectedItem; 
MessageBox.Show(row["Prescription"].toString() + " " + row["Date"].toString()); 

WPFは、データグリッドにバインド提供したように、これはかなり透明であるべきです。ただし、次のメソッドは、SQLDataAdapterを使用し、DataGridColoumnsへのバインディングパスを提供した場合にのみ機能します。たとえば。上記のデータグリッドがgrid1という名前で、列を自動的に生成してfalseに設定し、列名をヘッダーにバインドするバインディングを使用しているとします。この場合、 'DataRowView'型の 'row'変数を使用して、選択した行を格納します。次に、バインドパスを使用して、選択した行の個々の列を参照します。 これが役立つことを願っています!乾杯!

PS:SelectionUnitは=「行」

0

[OK]をリバースエンジニアリングし、反射の小さな妖精の塵を行った後、1にかかわらずのすべてを(得るために(任意の時点で)SelectedCellsに対してこの操作を行うことができれば作品一方から多くの選択されたセルにデータが1列または多数列に)選択:

MessageBox.Show(

string.Join(", ", myGrid.SelectedCells 
         .Select(cl => cl.Item.GetType() 
              .GetProperty(cl.Column.SortMemberPath) 
              .GetValue(cl.Item, null))) 

       ); 

Iは、DateTimeフィールドは、インクルードはToString()を開始する値を返すべきであるのみのにテキスト(文字列)フィールドでこれを試みました。また、SortMemberPathHeaderと同じではないので、常に反映される適切なプロパティを提供する必要があります。

<DataGrid ItemsSource="{Binding MyData}"      
      AutoGenerateColumns="True" 
      Name="myGrid" 
      IsReadOnly="True" 
      SelectionUnit="Cell" 
      SelectionMode="Extended"> 
0

これは本当に答えではない、あなたがにSO提供と私は同じくらいでは(私のためにパズルを解く)以下にRushiによって溶液

var cellInfo = Grid1.SelectedCells[0]; 
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text; 
関連する問題