从wpf中检索gridview选定行的值



我是WPF新手。

我试图在尊重的文本框中检索gridview选定行的值。

在windows应用程序中,我通常这样做:

txtPartyCode=gv.SelectedRows[0].Cells[1].Value.ToString();

但我很困惑,如何使用WPF?

我试着:

txtPartyCode.Text=gvCust.SelectedItem[0]

但是,红色的工具提示出现在代码下面:can not apply index with [] to an expression of type object.

请帮帮我。如何使用WPF?

这里我很困惑你的数据类型是什么。将其传递给数据网格的ItemsSource属性。

如果您正在使用DataTable并将其传递给datagrid,那么下面的代码将为您工作。

void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {                   
            DataRowView rowview = dataGrid1.SelectedItem as DataRowView;
            if (rowview != null)
            {
             textbox1.Text=  rowview.Row.ItemArray[0].ToString();
            }            
        }

,如果你使用类型化对象的itemsSource属性的数据网格,例如员工列表。这是你可以做的。

 Employee emp  = dataGrid1.SelectedItem as Employee
if(emp !=null)
{
textBox1.Text =  emp.Name;
}
 private void YourGridName_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {               
          string fc = null;                   
          foreach (var item in e.AddedCells)
           {                        
            fc =((System.Data.DataRowView(item.Item)).Row.ItemArray[0].ToString();
           }
         }

您可以尝试为DataGrid SelectionChanged事件添加处理程序,如下所示:

private void dataGrid1_SelectionChanged(object sender, RoutedEventArgs e)
{
       DataRowView rowview = gv.SelectedItem as DataRowView;
       string textNeeded = rowview.Row[0].ToString();
}

最新更新