在WPF中将某张表中的数据显示到datagrid

a.在.xaml文件中拖入一个datagrid,然后添加列名,使用Binding="{Binding 数据库中的

列名称}",如下:  

<DataGrid AutoGenerateColumns="False" Height="438"HorizontalAlignment="Left" Margin="23,278,0,0" Name="dataGrid1"  VerticalAlignment="Top" Width="1249">            

    <DataGrid.Columns>                

    <DataGridTextColumn Width="100" FontSize="15" Header="编号" Binding="{Binding id}"/>                           

    <DataGridTextColumn Width="140" Header="名称" FontSize="15"  Binding="{Binding name}"/>                

     </DataGrid.Columns>        

</DataGrid>

b.首先把要显示的数据查询后放入datatable中   

public DataTable Show()        

{            

DataTable dt = new DataTable();            

try            

{                

if (DBHelper.connection.State == ConnectionState.Closed)                    

DBHelper.connection.Open();                

string sql = "查询语句";                

DataSet ds = new DataSet();                

SqlDataAdapter sda = new SqlDataAdapter(sql,DBHelper.connection);                

sda.Fill(ds, "虚拟表名");                

dt= ds.Tables["虚拟表名"];            

  }            

catch (Exception ex)            

{                

       MessageBox.Show(ex.Message);            

}            

      return dt;        

}

//注意:该方法中的虚拟表名就是一个自己定义的表名称

c.然后在后台代码编辑处将datatable中的数据与datagrid绑定  

dataGrid1.ItemsSource = Show().DefaultView;

转载于:https://www.cnblogs.com/jnyyq/p/3204196.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值