令人头疼的一件事是 SQL 注入和使用参数化查询,例如:
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='@1'", connection);
command.Parameters.AddWithValue("@1", textBox8.Text)
尽管您通常最好使用 SQL 数据库,但您所做的事情是完全可以接受的。
编辑:
以下是将业务逻辑与 GUI 分开的方法:
Class BusLogic
{
public List<string> ListboxItems = new List<string>();
public void PopulateListBoxItems(string userName)
{
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb";
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='@1'", connection);
command.Parameters.AddWithValue("@1", userName)
reader = command.ExecuteReader();
while (reader.Read())
{
ListboxItems.Add(reader[1].ToString()+","+reader[2].ToString());
}
}
}
}
GUI
private void button3_Click(object sender, EventArgs e)
{
var busLogic = new BusLogic();
busLogic.PopulateListBoxItems(textBox8.Text);
\\listBox1.Items.Clear();
ListboxItems.DataSource = busLogic.ListboxItems;
}
这种“MVC”方法的优点在于,如果我们依赖使用 Binding 绑定的控件,那么我们只需要测试 BusLogic。
ps 理想情况下ListboxItems
将是 IEnumerable 而不是 List,这样我们就不会向调用者公开任何添加/删除等功能。这是很好的 API 设计。