簡體   English   中英

WPF:從選定的行中獲取列名

[英]WPF: Get column name from selected row

我正在嘗試從DataGrid的wpf中的選定項中獲取行的特定列。

DataGrid的名稱為Datagrid_Newsale

選擇它時,我會收到整行的警報,因此我嘗試映射其列。

說行是否-

{ ID = 3, CustomerName = xyz, SaleDate = 05.08.2013 00:00:00, TotalAmount = 10 }

然后在文本框中顯示CustomerName=xyz列。

獲取行

var copyitem = Datagrid_NewSale.SelectedItem;

if (copyitem == null)
{
    MessageBox.Show("Please select values from list");
}
if (copyitem != null)
{                       
    MessageBox.Show(copyitem.ToString());
}

為了讓customerName進入文本框,我嘗試創建一個新的model實例-

public class CustomerDetailes
{
    public string CustomerName { get; set; }
}

以及來自客戶表的數據庫中的值

public void viewcustomername()
{
    List<CustomerDetailes> ilist = null;
    ilist = (from order in db.Customer
                select new CustomerDetailes
                {
                    CustomerName= order.CustomerName
                }).ToList();
    txtCustumer.Text = ilist.ToString();

}

因此,再嘗試一下-

CustomerDetailes copyitem = (CustomerDetailes)Datagrid_NewSale.SelectedItem;

if (copyitem == null)
{
    MessageBox.Show("Please select values from list");
}
if (copyitem != null)
{                       
    MessageBox.Show(copyitem.ToString());
}

txtCustomer.text=copyitem.CustomerName;  //CustomerName into a textbox

但它在copyitem中引用null。

如何從整行中獲取特定的列。

您必須將DataGrid的ItemsSource綁定到CustomerDetails集合,才能在SelectedItem中獲取CustomDetails。

在您的視圖模型中創建屬性(如果使用MVVM)或在諸如

List<CustomerDetails> customerDetails = new List<CustomerDetails>();
    List<CustomerDetails> MyCollection
    {
        get
        {

            return myList;
        }
        set
        {
            myList = value;
            PropertyChanged(this, new PropertyChangedEventArgs("MyCollection"));
        }
    }

在xaml中就可以了。

<DataGrid ItemsSource="{Binding MyCollection}"/>

或者,如果您直接在Datagrid中填充商品,則添加CustomerDetails實例,例如

dataGrid.Items.Add(new CustomerDetails(){Name = "abc"}, xyz propertis)

謝謝

如果您可以通過選擇事件訪問網格,則應在下面為您提供列((DataGrid)sender).CurrentCell.Column.Header

並使用列名到您要顯示的對象的屬性的一些映射

我想出了這個簡單的解決方案。

在我的情況下, copyitem數據類型為Anonymous。 在這種情況下,使用Dynamic數據類型解決了我的問題。

由於我的數據是動態發送的,然后我試圖映射出特定的列,因此實際上不可能靜態地執行此操作,因為那時沒有數據。

使用動態數據類型-

 dynamic copyitem = dataGrid1.SelectedItem;

訪問屬性-

int localId = copyitem.ID;

此外,對於customerName,TotalAmount我也做同樣的事情。

Linq查詢更改-

var query= (from order in db.Customer
where order.ID=localId
select order).ToList();

DataGrid_OpenSale.ItemsSource=query //將數據返回到另一個數據網格。

在VB中⠀⠀⠀

Private Sub SCUSTDataGrid_GotFocus(sender As Object, e As RoutedEventArgs) Handles SCUSTDataGrid.GotFocus
  Dim og As DataGridCell = e.OriginalSource
  Dim ccontent As TextBlock = og.Content
  Dim dg As DataGrid
  dg = e.Source
  Dim selcol As String = dg.CurrentCell.Column.Header.ToString

  MessageBox.Show(selcol.ToString + ccontent.Text + " got focus event")
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM