Mah*_*oud 1 c# datagridview winforms
我正在尝试dataGridView使用数据库中的数据填充 a ,它必须在加载表单和refreshButton单击时获取数据。
这是代码:
public partial class PhoneBookMainWindow : Form
{
static public string connString = "Server=(local); Database=PhoneBook; Trusted_Connection=TRUE";
public SqlConnection connection = new SqlConnection(connString);
private void btnRefreshPhoneBook_Click(object sender, EventArgs e)
{
SqlCommand command = new SqlCommand("SELECT ID, contactName, jobTitle, currentAddress, workAddress, workPhone, cellPhone FROM ContactsInformations", connection);
try
{
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = command;
DataTable dataSet = new DataTable();
dataAdapter.Fill(dataSet);
BindingSource bindingSrc = new BindingSource();
bindingSrc.DataSource = dataSet;
dataGridView1.DataSource = bindingSrc;
dataAdapter.Update(dataSet);
}
catch (Exception x)
{
MessageBox.Show(x.Message);
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在Form loading& 中使用相同的代码btn clicking并且它们在执行中正常工作,但是当我从数据库中删除一行时出现问题(使用单击 a 查询delete btn然后单击refresh btn展览来到我面前。
您似乎面临的问题是您有多个代码块共享同一个SqlConnection对象。撇开潜在的竞争条件不谈,这意味着它们中的任何一个都可能会在另一个对象使用它之前尝试处理该对象。
处置后,该对象不再处于可以使用它的状态。特别是在这种情况下,它不再有.ConnectionString集合。
本质上,这正在发生:
创建SqlConnection对象并不是一个特别耗费资源的过程,因此最好将它的范围限定在将要使用它的代码的本地范围内。像这样的东西:
using (SqlConnection connection = new SqlConnection(connString))
{
using (SqlCommand command = new SqlCommand("SELECT ID, contactName, jobTitle, currentAddress, workAddress, workPhone, cellPhone FROM ContactsInformations", connection))
{
try
{
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = command;
DataTable dataSet = new DataTable();
dataAdapter.Fill(dataSet);
BindingSource bindingSrc = new BindingSource();
bindingSrc.DataSource = dataSet;
dataGridView1.DataSource = bindingSrc;
dataAdapter.Update(dataSet);
}
catch (Exception x)
{
MessageBox.Show(x.Message);
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里做了两件事:
SqlConnection对象在方法的内部,而不是在类级创建。这意味着除了这个方法会使用它之外什么都没有。(所以除了这个方法没有什么可以打破它。)using语句中包装了一些一次性对象,这是处理任何实现IDisposable.| 归档时间: |
|
| 查看次数: |
2430 次 |
| 最近记录: |