【发布时间】:2018-11-21 01:16:45
【问题描述】:
我正在尝试将我的数据库连接到我的ListView,并且我正在尝试找到比书中介绍的更好的方法。我查看了几个论坛,其中很多都与下面我的代码中的内容相同。
我们没有太多时间在课堂上复习数据库,所以我对连接字符串的很多知识都来自互联网和书中的一小章。
我的数据库名称是GameStoreLibrary .
using System.Data;
using System.Data.SqlServerCe;
public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(@"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");
private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);
try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
【问题讨论】:
-
了解 MVVM。
-
你是指 WPF 还是 WinForms?
-
那不是 WPF...
-
哎呀,我的意思是 WinForms,我很抱歉
-
不要尝试在整个班级中重复使用相同的连接对象。为每个查询创建并处置一个新对象,并且只共享连接字符串。由于有一个称为连接池的功能,因此效果更好。
标签: c# winforms sql-server-ce