使用 SQL Server Compact 3.5 Sp1 的 DataGrid in WPF






4.88/5 (16投票s)
使用 SQL Server Compact 3.5 Sp1 的 DataGrid in WPF
引言
Windows Presentation Foundation(简称 WPF)是 Windows Forms 的改进技术。WPF 的主要优势在于用户界面设计,开发者可以使用 2D 和 3D 渲染、自适应文档、字体排印、矢量图形、运行时动画和预渲染媒体来实现出色的设计。
背景
本文将帮助您创建一个简单的 WPF 应用程序,使用 SQL Server Compact 3.5 sp1 作为数据源在 datagrid
中绑定数据。在本文中,我想展示在 WPF 中将数据绑定到 datagrid
的简单方法。
先决条件
- Visual Studio 2008/2010
- SQL Server 2008
Using the Code
在本文中,我使用了 Visual Studio 2010 来演示示例。以下是创建新 WPF 项目的步骤。
创建新的 WPF 项目
步骤 1:点击 开始 -> 所有程序 -> Microsoft Visual Studio 2010 -> Microsoft Visual Studio 2010
步骤 2:点击“新建项目”
步骤 3:在“Visual C#” -> Windows -> WPF 应用程序下
为您的新 WPF 应用程序命名,并指定位置和解决方案名称。
开始使用 WPF 进行设计和编程
设计窗口或 Web 应用程序非常简单且有趣。让我们开始设计第一个 WPF 应用程序。
WPF 会生成类似于 HTML 的 XAML 标签。在这里,我使用了以下工具进行设计:
fName_lbl
-> “名字” LabelfName_Txt
-> TextboxlName_lbl
-> “姓氏” LabellName_Txt
-> TextboxDOB_lbl
-> “出生日期” LabelDOB_Txt
-> Date PickerCity_lbl
-> “城市” LabelCity_Txt
-> Combo BoxNew_Btn
-> “新建” ButtonAdd_Btn
-> “添加” ButtonDel_Btn
-> “删除” ButtonUpdate_Btn
-> “更新” Button
Datagrid1
将数据绑定到 WPF 中的“Datagrid1
”很简单,在此示例中,我使用了 ADO.NET 进行绑定。
<datagrid width="481" height="199" name="dataGrid1"
selectedcellschanged="dataGrid1_SelectedCellsChanged"
canuserresizerows="False" loaded="dataGrid1_Loaded"
itemssource="{Binding Path=MyDataBinding}" verticalalignment="Top"
margin="14,65,0,0" horizontalalignment="Left" grid.row="4" autogeneratecolumns="False">
<datagrid.columns>
<datagridtextcolumn width="120" isreadonly="True"
header="First Name" binding="{Binding Path=fName}">
<datagridtextcolumn width="110" isreadonly="True"
header="Last Name" binding="{Binding Path=lName}">
<datagridtextcolumn width="150" isreadonly="True"
header="Date Of Birth" binding="{Binding Path=DOB}">
<datagridtextcolumn width="90" isreadonly="True"
header="City" binding="{Binding Path=City}">
</datagridtextcolumn></datagridtextcolumn><
/datagridtextcolumn></datagridtextcolumn></datagrid.columns>
</datagrid>
我们可以通过将数据分配给 datagrid
的“ItemsSource
”并指定连接数据库以获取数据的 datagrid
路径来绑定数据。这是 WPF 的一项附加功能。
App.config 是一个包含应用程序设置和其他内容的配置文件。在这里,我用它来存储数据库 connectionstring
,内容如下:
<configuration>
<connectionstrings>
<add name="ConnectionString1"
connectionstring="Data Source=(Database file location goes here)
\DatabindusingWPF.sdf; Password=test@123; Persist Security Info=False;">
</add></connectionstrings>
</configuration>
在这里,我使用了 SQL Server Compact 3.5 sp1 作为我的数据源,因此我们需要提供数据库文件存储的确切路径。(**注意**:您需要提供数据库文件的确切路径才能使此代码正常工作。)
每当我们添加、删除、更新时,datagrid
都需要相应地进行更改,因此我创建了一个名为“BindGrid()
”的 public
方法。
// Establishing Connection String from Configuration File
string _ConnectionString = ConfigurationManager.ConnectionStrings
["ConnectionString1"].ConnectionString;
public void BindGrid()
{
SqlCeConnection _Conn = new SqlCeConnection(_ConnectionString);
// Open the Database Connection
_Conn.Open();
SqlCeDataAdapter _Adapter = new SqlCeDataAdapter("Select * from Details", _Conn);
DataSet _Bind = new DataSet();
_Adapter.Fill(_Bind, "MyDataBinding");
dataGrid1.DataContext = _Bind;
// Close the Database Connection
_Conn.Close();
}
在上面,我展示了一种非常简单的方法来获取连接到数据库的 SQL 连接字符串,并使用数据集将数据绑定到 datagrid
。下面的代码将使用 textbox
中的值添加新记录。
添加新记录
要在数据库中添加新记录,我使用了一个简单的 INSERT 查询,它将填充到 datagrid
中。以下代码将实现此目的:
private void Add_Btn_Click(object sender, RoutedEventArgs e)
{
try
{
SqlCeConnection _Conn = new SqlCeConnection(_ConnectionString);
// Open the Database Connection
_Conn.Open();
string _Date = DOB_Txt.DisplayDate.ToShortDateString();
// Command String
string _Insert = @"insert into Details
(fName,lName,DOB,City)
Values('" + fName_Txt.Text + "','" + lName_Txt.Text + "','" +
_Date.ToString() + "','" + City_Txt.Text + "')";
// Initialize the command query and connection
SqlCeCommand _cmd = new SqlCeCommand(_Insert, _Conn);
// Execute the command
_cmd.ExecuteNonQuery();
MessageBox.Show("One Record Inserted");
fName_Txt.Text = string.Empty;
lName_Txt.Text = string.Empty;
DOB_Txt.Text = string.Empty;
City_Txt.Text = string.Empty;
this.BindGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
为了仅将日期存储到数据库中,我使用了“ToShortDateString
”,它会截断时间。
string _Date = DOB_Txt.DisplayDate.ToShortDateString();
为了确认记录已添加,我有一个带有消息“已插入一条记录”的 messagebox
,一旦您单击“确定”,您应该会在 datagrid
中看到已添加的记录(请参阅下图)。
private void Del_Btn_Click(object sender, RoutedEventArgs e)
{
try
{
SqlCeConnection _conn = new SqlCeConnection(_ConnectionString);
// Open Database Connection
_conn.Open();
// Command String
string _DelCmd = @"Delete from Details
Where fName='" + fName_Txt.Text + "'";
// Initialize the command query and connection
SqlCeCommand _CmdDelete = new SqlCeCommand(_DelCmd, _conn);
// Execute the command
_CmdDelete.ExecuteNonQuery();
MessageBox.Show("One Record Deleted");
fName_Txt.Text = string.Empty;
lName_Txt.Text = string.Empty;
DOB_Txt.Text = string.Empty;
City_Txt.Text = string.Empty;
this.BindGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
要更新现有数据,只需双击 datagrid
上的记录,值将被编辑,并显示在各自的 textbox
中,如下图所示。
下面的代码将执行 datagrid
值的编辑:
DataRowView _DataView = dataGrid1.CurrentCell.Item as DataRowView;
if (_DataView != null)
{
fName_Txt.Text = _DataView.Row[0].ToString();
fName_Txt.IsEnabled = false;
lName_Txt.Text = _DataView.Row[1].ToString();
DOB_Txt.Text = _DataView.Row[2].ToString();
City_Txt.Text = _DataView.Row[3].ToString();
}
在这里,我使用了“DataRowView
”来读取 datagrid
的 currentcell
并获取每个单元格的值,然后将其分配给一个 textbox
。
您无法更改名字,因为我们将其值用作数据库中的主键,因此您可以更改其他可用字段。在此示例中,我已将姓氏更改为“Sellamuthu
”。
更新代码
private void Update_Btn_Click(object sender, RoutedEventArgs e)
{
try
{
SqlCeConnection _Conn = new SqlCeConnection(_ConnectionString);
// Open Database Connection
_Conn.Open();
string _Date = DOB_Txt.DisplayDate.ToShortDateString();
// Command String
string _UpdateCmd = @"Update Details Set
lName = '" + lName_Txt.Text + "',
DOB = '" + _Date.ToString() + "',
City = '" + City_Txt.Text + "'
where fName = '" + fName_Txt.Text + "'";
// Initialize the command query and connection
SqlCeCommand _CmdUpdate = new SqlCeCommand(_UpdateCmd,_Conn);
// Execute the command
_CmdUpdate.ExecuteNonQuery();
MessageBox.Show("One Record Updated");
fName_Txt.Text = string.Empty;
lName_Txt.Text = string.Empty;
DOB_Txt.Text = string.Empty;
City_Txt.Text = string.Empty;
this.BindGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
我使用 Update
查询,通过引用主键“First Name
”来更新数据库中的记录。
结论
这样,我们就使用 Visual Studio 2010 和 SQL Server Compact 创建了一个新的 WPF 应用程序。编程愉快。:-)
历史
- 2011 年 2 月 5 日:初始帖子