【问题标题】:How to display data from datagrid to textbox in wpf c#如何在wpf c#中将数据从数据网格显示到文本框
【发布时间】:2014-03-25 21:12:30
【问题描述】:

可以给我一个例子或代码,如何在 c# - wpf 应用程序中将数据从数据网格显示到文本框。

我试过像在 Windows 窗体应用程序中那样做,但代码不起作用。

if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

            name.Text = row.Cells["Name"].Value.ToString();
            lastName.Text = row.Cells["LastName"].Value.ToString();
            userName.Text = row.Cells["UserName"].Value.ToString();
            password.Text = row.Cells["Password"].Value.ToString();
        }

【问题讨论】:

  • @HamletHakobyan 我已经更新了帖子
  • @HamletHakobyan 什么都没有,因为我不知道如何:s

标签: c# wpf datagrid textbox wpfdatagrid


【解决方案1】:

首先,WPF 不是 WinForms,尝试以相同的方式编写代码只会让您感到痛苦。你想要做的实际上在 WPF 中真的很容易!最短的解决方案是直接绑定到 DataGrid SelectedItem 属性:

<DataGrid x:Name="UserGrid" ItemsSource="{Binding Users}">
...
</DataGrid>

<TextBox Text="{Binding ElementName=UserGrid, Path=SelectedItem.Name}"/>
...More of the same...

现在假设 DataGrid 绑定到您的 ViewModel(而不是您的代码隐藏)中的“用户”类(它绝对应该是)的集合。另一种方法是绑定 SelectedItem,然后让其他控件绑定到该控件,如下所示:

<DataGrid x:Name="UserGrid" ItemsSource="{Binding Users}" SelectedItem="{Binding CurrentUser}">
...
</DataGrid>

<TextBox Text="{Binding Path=CurrentUser.Name}"/>
...More of the same...

当然,您现在需要在 ViewModel 中绑定一个“CurrentUser”属性。两种方法都是同样有效的方法,只需决定您更喜欢哪种方法。如果您需要“CurrentUser”对象来处理代码中的其他内容,则第二种方法会更好,第一种方法会更快一些,并且如果您不需要它则没有 shell 属性。如果您还没有使用 MVVM,这里有一个很棒的教程 (MSDN)。

【讨论】:

  • 还有一个问题?我有 10 个文本框,只有 7 个显示数据……我一定做错了什么。哪些数据是 Path=SelectedItem.Name...我在哪里可以找到“名称”名称?
  • 好的,太好了!如果您遇到其他问题,请告诉我。对于遇到此问题的任何其他人的快速回答,“SelectedItem.Name”表示查看“ElementName”中命名的元素的“SelectedItem”对象,然后获取其“Name”属性。
  • 完全正确。非常感谢您的宝贵时间!欣赏它
猜你喜欢
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多