如何在数据网格中选择所选行的对象 [英] HOW TO SELECT THE OBJECT OF SELECTED ROWS IN DATA GRID

查看:72
本文介绍了如何在数据网格中选择所选行的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I create one table and data grid control and two Colum that is id and name and two textbox id and name .I want that when I click on my grid the selected value will display on their cross ponding textbox such as id and name.   I create I button for show that show the value that is store in database and one button is update I want when I click on update button the selected row in data grid is display in tbxid and tbxname text box in my form . 

I done following code on show button 
 private void button Click(object sender, RoutedEventArgs e) {
        var data = from p in db.gridtbls select p;
        myDataGrid.ItemsSource = data.ToList();

    }

and I used following coding on update button var id = myDataGrid.SelectedValue; tbxname.Text = id.ToString(); tbxid.Text = id.ToString();

but we get the value in textbox name is such as {ID=1 Name="aqib '} is shown in txbname text box . I want that only print in name textbox is "aqib" and id is "1".

how we solve it.

​

推荐答案

最简单的方法是使用内置数据绑定来获取用户选择。

The simplest way is to use the built in data binding to get user selections.
// Example data binding class
public class MyData
{
  public int Id { get; set; }
  public string Name { get; set; }
}





XAML用于显示数据



XAML for displaying the data

<listview x:name="lst_Data" xmlns:x="#unknown">
 <listview.view>
  <gridview>
   <gridview.columns>
    <gridviewcolumn header="ID" displaymemberbinding="{Binding Id}" />
    <gridviewcolumn header="Name" displaymemberbinding="{Binding Name}" />
   </gridview.columns>
  </gridview>
 </listview.view>
</listview>





And在这里加载和绑定数据时沿着这些方向的东西



And something along these lines when loading and binding the data here

public void LoadMyData()
{
 MyData[] _myData = FetchMyData(); // All you really need is an IEnumerable to bind data to
 lst_Data.DataContext = typeof(MyData);
 lst_Data.ItemsSource = _myData;
}



然后获取最终用户选择的数据


And then to get which data is selected by the end user

public void UserSelectedSomething(object sender, EventArgs e)
{
 if (lst_Data.SelectedItem == null)
   return;
 
 MyData selectedData = lst_Data.SelectedItem as MyData;

 if (selectedData == null)
   // Oops!  Handle
 else
   // Do something with data
}


这篇关于如何在数据网格中选择所选行的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆