Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i wanna to do the best for this code i wanna to open the connection one time and bound two dropdownlist . the code worked correctly but i wish to learn the best to use open and close connection one time
C#
string str1 = "select eq_type_name + '-'+ eq_type_name_arabic as txtField,eq_type_no from equit_type;";
               string str2 = "SELECT ID, name FROM MendCompany";
               OleDbConnection conn = new OleDbConnection(cc);
               OleDbCommand cmd = new OleDbCommand(str1, conn);
               conn.Open();

               Dr_device.DataSource = cmd.ExecuteReader();
               Dr_device.DataTextField = "txtField";
               Dr_device.DataValueField = "eq_type_no";
               Dr_device.DataBind();
               conn.Close();
               conn.Open();
               cmd.CommandText = str2;
               Dr_kind0.DataSource = cmd.ExecuteReader();
               Dr_kind0.DataTextField = "name";
               Dr_kind0.DataValueField = "ID";
               Dr_kind0.DataBind();
               conn.Close();
               Dr_device.Items.Insert(0, " اختر الجهاز");
               Dr_kind0.Items.Insert(0, "**اختر شركة الإصلاح**");


What I have tried:

open connection 2 time is my tired
Posted
Updated 24-Sep-16 7:47am
Comments
[no name] 24-Sep-16 11:52am    
Do you think that the conn.Close() has something to do with it?

No this is one of those things that is too glaringly obvious that I feel like I am missing something. But in your code you have

C#
Dr_device.DataBind();
               conn.Close();
               conn.Open();
               cmd.CommandText = str2;


You close the connection and are re-openning it yourself. Remove the conn.Close and conn.Open as you open the connection earlier in your code and close it farther down in your code.
 
Share this answer
 
Comments
Muhammed Elwany 24-Sep-16 13:50pm    
it will make error
As already stated you close and reopen then connection and you have no reason to do that. Afetr opening the connection, fetch the data you need, do the operations you want to and then close the connection. There is no limit how many operations are allowed within a single connection.

When working with connections, commands, and so on, remember to:
- use using statements
- open as late as possible
- close as soon as possible (but do all operations in between)
- handle errors

For examples, have a look at Properly executing database operations[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900