I am in this situtation : view image
there are 5 user controls stacked in the empty panel.
I have a vertical menu in which there are several buttons and when I click on a button, I use : BringToFront()
for displaying them .
private void Button1_Click(object sender, EventArgs e)
{
tabRandom1.BringToFront();
}
each usercontrol
contains datagridview
, and other elements
that have to be loaded with the data coming from database, but I would like that if I click on button1
, only that the elements of usercontrol1
be loaded .
when i tried :
private async void UserControl1_Load(object sender, EventArgs e)
{
this.DataGridView1.DataSource = await GetDataAsync();
}
i get a exception @er-shoaib :
there is already an open DataReader associated with tis connection which must be closed first.
I am looking for the best way to load the elements of the active usercontrol
Error you are getting is clearly saying you have already opened DataReader
.
You cannot have more than one opened DataReader
inside one connection.
In order to make your code for communication with database more stable write code with using
and it will automatically dispose of objects like this:
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
}
or if you opened one connection for let's say whole class (like i think you did up there) just do not wrap SqlConnection con = new Sql....
inside using
but everything others do and you will have no problem expect do not forget to do connection.Close()
.
I am ALWAYS using using
for every component in sql connection and it is not affecting my performance.
When you reorganize code this way you will get rid of that problem, but one advice is not to load data when someone open form since you will load it 5 times and user may use only one but better create method like RefreshData()
inside your UC and before you do yourUserControl.BringToFront();
you also do yourUserControl.RefreshData()
and this way you will load it only if needed and you will always have fresh one plus you will have easy method for refreshing data if needed anywhere.