2012-02-24 30 views
0

從Datagrid的 我已經實現了它使用的數據表如何使編輯/從Datagrid的

 DataTable _datatable = new DataTable(); 
     DataRow _datarow; 

我在這裏發起的數據,我想問問添加/刪除項目如何使編輯/添加/刪除項目,如何修改此數據 如何從數據網格中獲取數值並與數據網格進行交互 。 List list = _datatable.AsEnumerable()。ToList();

我已將其轉換爲List,並從那裏獲取數據?這是不是一個好主意 。

我希望能夠更新,插入和刪除。

回答

0

,如果你不這樣做MVVM,你可以簡單地設置的DataGrid的ItemsSource到您的數據表

this.dgMyDataGridControl.ItemsSource= this._mydatatable; 

不要忘記爲你的數據網格的屬性設置爲你想要的東西(CanUserAddRows,...)

這當然只是更新,刪除和修改您的數據表中的數據而不是數據庫中的數據。

0

您可以使用簡單的對象列表。然後創建一個DataGrid並將DataRecordList綁定到它。 前端應該是這樣的:

<Window x:Class="TestDataGrid.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:Data="clr-namespace:TestDataGrid" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.Resources> 
    <ResourceDictionary> 
     <Data:DataRecordList x:Key="DataSource"/> 
     <CollectionViewSource x:Key="DataCollection" Source="{StaticResource DataSource}"/> 
    </ResourceDictionary> 
</Window.Resources> 
<Grid> 
    <DataGrid Name="GridData" 
     ItemsSource="{Binding Source={StaticResource DataCollection}}" 
     AutoGenerateColumns="False" 
     CanUserDeleteRows="True" CanUserAddRows="True"> 
     <DataGrid.Columns> 
      <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/> 
      <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/> 
      <DataGridTextColumn Header="SomeValue" Binding="{Binding Path=SomeValue}"/> 
     </DataGrid.Columns> 
    </DataGrid> 
</Grid> 
</Window> 

和後面的代碼是這樣的:

namespace TestDataGrid 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 
    } 

    public class DataRecord 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public string SomeValue { get; set; } 
    } 

    public class DataRecordList : List<DataRecord> 
    { 
     public DataRecordList() 
     { 
      this.Add(new DataRecord() { ID = 1, Name = "Johnny", SomeValue = "Dummy" }); 
      this.Add(new DataRecord() { ID = 2, Name = "Grace", SomeValue = "Foo" }); 
      this.Add(new DataRecord() { ID = 3, Name = "Steve", SomeValue = "Bar" }); 
     } 
    } 
} 

您可以添加行,刪除行,甚至編輯行以及排序和重新排序列。 享受。 JiKra