• 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);
        }
    }

    拣尽寒枝不肯栖,寂寞沙洲冷。
  • 相关阅读:
    提高php代码效率的几点
    jquery各种操作复选框(全选、全不选、自动勾选、反选……)
    封装PDO单例模式类
    Git常用命令
    简化版的sqlserver分页
    Sql Server 数据分页
    Linux 下动态链接库搜索路径问题
    mysqlperformanceblog
    vim 退格键(backspace)不能用
    Linux vi/vim 编辑命令总结
  • 原文地址:https://www.cnblogs.com/leischen/p/2829640.html
Copyright © 2020-2023  润新知