WPF DataGrid使用簡介

1)自動生成列

<DataGrid AutoGenerateColumns="True" Name="datagrid" CanUserAddRows="False" MouseDoubleClick="datagrid_MouseDoubleClick" />

2)取消自動生成列,手動綁定到相應字段

<DataGrid AutoGenerateColumns="False" Name="datagrid" CanUserAddRows="False" MouseDoubleClick="datagrid_MouseDoubleClick">
<DataGrid.Columns>
<DataGridTextColumn Header="編號" Binding="{Binding ID}"></DataGridTextColumn>
<DataGridTextColumn Header="公司" Binding="{Binding CompanyName}"></DataGridTextColumn>
<DataGridTextColumn Header="固定資產" Binding="{Binding FixedAssets}" Width ="*"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>

最後一列設置Width ="*"是爲了取消空白列。

(3)後臺代碼

private void Window_Loaded(object sender, RoutedEventArgs e)
{
datagrid.ItemsSource = AccessDAL.OleDbHelper.ExecuteDataTable("SELECT * from Customers").DefaultView;
}

//雙擊DataGrid,顯示相應信息

private void datagrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DataRowView row = datagrid.SelectedItem as DataRowView;
MessageBox.Show(row["id"].ToString());
}

//若是綁定到對象集合,如ObservableCollection<Employee>,代碼以下:

ObservableCollection<Employee> col;
public EmployeeManage()
{
InitializeComponent();
col = new ObservableCollection<Employee>();
col.Add(new Employee() { Id = 1, Name = "Jim", Salary = 2500.50f });
col.Add(new Employee() { Id = 2, Name = "John", Salary = 2600.50f });
datagrid.ItemsSource = col;
}

private void datagrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Employee emp=datagrid.SelectedItem as Employee;
MessageBox.Show(emp.Id.ToString());
}

(4)刪除選中的多行數據

private void Delete_Click(object sender, RoutedEventArgs e)
{
for (int i = datagrid.SelectedItems.Count - 1; i >= 0; i--)
{
Good good = datagrid.SelectedItems[i] as Good;
goods.Remove(good);
}
}
相關文章
相關標籤/搜索