使用多个用户控件从 Mysql 数据库加载大数据的最佳方法
best way to load large data from Mysql Database using multiple usercontrols
我现在的情况是:view image
空面板中堆叠了 5 个用户控件。
我有一个垂直菜单,其中有几个按钮,当我单击一个按钮时,我使用:BringToFront()
来显示它们。
private void Button1_Click(object sender, EventArgs e)
{
tabRandom1.BringToFront();
}
每个 usercontrol
包含 datagridview
和其他 elements
必须加载来自数据库的数据,但如果我单击 button1
, 仅加载 usercontrol1
的元素。
当我尝试时:
private async void UserControl1_Load(object sender, EventArgs e)
{
this.DataGridView1.DataSource = await GetDataAsync();
}
我得到一个例外@er-shoaib :
there is already an open DataReader associated with tis connection which must be closed first.
我正在寻找加载活动用户控件元素的最佳方法
您遇到的错误显然是说您已经打开了 DataReader
。
您不能在一个连接中打开多个 DataReader
。
为了让你与数据库通信的代码更稳定写代码using
它会自动处理这样的对象:
using(SqlConnection con = new SqlConnection("..."))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("...", con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.Read())
// Do the things
}
}
// Do not need close since connection will be disposed
}
或者如果你打开一个连接让我们说整个 class (就像我认为你在那里所做的那样)只是不要将 SqlConnection con = new Sql....
包装在 using
内但其他人所做的一切和你一样不会有问题期望不要忘记做 connection.Close()
.
我总是对 sql 连接中的每个组件使用 using
,这不会影响我的表现。
当您以这种方式重新组织代码时,您将摆脱这个问题,但一个建议是不要在有人打开表单时加载数据,因为您将加载它 5 次并且用户可能只使用一种但更好的创建方法,例如 RefreshData()
在你的 UC 中,在你做 yourUserControl.BringToFront();
之前你也做 yourUserControl.RefreshData()
这样你只会在需要时加载它并且你将始终有新鲜的一个加上你将有刷新数据的简单方法如果任何地方需要。
我现在的情况是:view image
空面板中堆叠了 5 个用户控件。
我有一个垂直菜单,其中有几个按钮,当我单击一个按钮时,我使用:BringToFront()
来显示它们。
private void Button1_Click(object sender, EventArgs e)
{
tabRandom1.BringToFront();
}
每个 usercontrol
包含 datagridview
和其他 elements
必须加载来自数据库的数据,但如果我单击 button1
, 仅加载 usercontrol1
的元素。
当我尝试时:
private async void UserControl1_Load(object sender, EventArgs e)
{
this.DataGridView1.DataSource = await GetDataAsync();
}
我得到一个例外@er-shoaib :
there is already an open DataReader associated with tis connection which must be closed first.
我正在寻找加载活动用户控件元素的最佳方法
您遇到的错误显然是说您已经打开了 DataReader
。
您不能在一个连接中打开多个 DataReader
。
为了让你与数据库通信的代码更稳定写代码using
它会自动处理这样的对象:
using(SqlConnection con = new SqlConnection("..."))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("...", con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.Read())
// Do the things
}
}
// Do not need close since connection will be disposed
}
或者如果你打开一个连接让我们说整个 class (就像我认为你在那里所做的那样)只是不要将 SqlConnection con = new Sql....
包装在 using
内但其他人所做的一切和你一样不会有问题期望不要忘记做 connection.Close()
.
我总是对 sql 连接中的每个组件使用 using
,这不会影响我的表现。
当您以这种方式重新组织代码时,您将摆脱这个问题,但一个建议是不要在有人打开表单时加载数据,因为您将加载它 5 次并且用户可能只使用一种但更好的创建方法,例如 RefreshData()
在你的 UC 中,在你做 yourUserControl.BringToFront();
之前你也做 yourUserControl.RefreshData()
这样你只会在需要时加载它并且你将始终有新鲜的一个加上你将有刷新数据的简单方法如果任何地方需要。