现在的位置: 首页 > 综合 > 正文

WPF连接数据库+显示数据到dataGrid

2013年02月07日 ⁄ 综合 ⁄ 共 1352字 ⁄ 字号 评论关闭

在这里我会讲述2种WPF连接到数据库的方式,也是初学WPF,希望各位别吐槽

(1)WPF支持直接用ado.net ,不像silverlight那样要通过RIA或者其他方式去连接数据库

所以我在这里先讲解直接用ado.net的用法

首先我们要在xaml页面拖一个dataGrid的控件

设置

AutoGenerateColumns="True"

在xaml.cs即后台

会用ado.net的童鞋都知道,要先添加头文件

using
System.Data.SqlClient;
using
System.Data;

然后才可以用ado.net

连接数据库代码如下:

string
sql =
"server=JOY;database=VofinePearl;uid=sa;pwd=123";//连接字符串
          
SqlConnection sqlcon = new
SqlConnection(sql);//
          
string sql1 =
"select ID from ProductLot";
          
SqlDataAdapter sqlada = new
SqlDataAdapter(sql1,sqlcon);
          
DataSet ds = new
DataSet();
          
ds.Clear();
          
DataTable table1 = new
DataTable();
          
sqlada.Fill(ds, "table1");
          
dataGrid1.DataContext= ds;

在这里我就不注释了,因为都是些简单的连接数据库装载到dataset里面的代码。

重要的是把数据装载dataGrid的方式

大家要注意,在后台要写上dataGrid.DataContext=ds;在前台要加上:ItemsSource="{Binding Path=table1}

下面是前台的代码

<DataGrid AutoGenerateColumns="True"
ItemsSource="{Binding Path=table1}"
Height="200"
HorizontalAlignment="Left"
Margin="41,89,0,0"
Name="dataGrid1"
VerticalAlignment="Top"
Width="456"
/>

执行后的结果是

(2)数据库实体类

1  拖一个dataGrid的控件到界面上

代码如下

<Grid>
       
<DataGrid AutoGenerateColumns="True"
Height="111"
HorizontalAlignment="Left"
Margin="66,140,0,0"
Name="dataGrid1"
VerticalAlignment="Top"
Width="331"
/>
    </Grid>

在项目下添加实体类模型

点击进去创建新连接

一直到后面,勾选表,然后完成,按F6生成一下。在菜单数据下->显示数据源能看到自己添加进来的实体类数据

调用在后台

tb_testEntities tb =
new tb_testEntities();
           
dataGrid1.ItemsSource = tb.info;

搞掂!

 

抱歉!评论已关闭.