【问题标题】:retrieve values in selected row of gridview from wpf从 wpf 中检索 gridview 的选定行中的值
【发布时间】:2013-06-07 12:39:46
【问题描述】:

我是 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 怎么做?

【问题讨论】:

  • 首先,没有普通的windows应用程序。我假设你在谈论 Winforms。你有没有想过使用Binding
  • gv.ItemsSource 的类型是什么?

标签: c# .net wpf visual-studio-2010


【解决方案1】:

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

如果您是使用数据表并将其传递给数据网格,那么下面的代码将为您工作。

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

如果您使用类型对象作为 DataGrid 的 itemsSource 属性,例如员工列表。那么在这里你可以做什么。

 Employee emp  = dataGrid1.SelectedItem as Employee
if(emp !=null)
{
textBox1.Text =  emp.Name;
}

【讨论】:

    【解决方案2】:
     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();
               }
             }
    

    【讨论】:

    • 在行选择时这个事件会被触发吗?
    • 是的,在您的数据网格设计器上执行属性-事件并添加事件
    • 错误 2 'System.Data.DataRowView' 是一个'类型',在给定的上下文 E:\WPFTuts\NewSoftWCF\NewSoftWCF\MainWindow.xaml.cs 103 19 NewSoftWCF 中无效跨度>
    • 错误 2 'System.Data.DataRow' 是一个'类型',在给定的上下文 E:\WPFTuts\NewSoftWCF\NewSoftWCF\MainWindow.xaml.cs 103 24 NewSoftWCF 中无效跨度>
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 2012-08-06
      相关资源
      最近更新 更多