Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The connection that the reader you are using is dependent on has been closed in the button_ShowUsers_Click event.</p> <p>It is not a good practice to try to share connections and DataReaders across events. That will result in open connections that are not disposed of correctly. A better practice would be to have the creation of the Connection, Command, and DataReader take place in each event method. By using the "using" statement they will be closed and disposed of correctly in each method. You can also remove the class level variable "rdr".</p> <pre><code>namespace Userform { public partial class Form1 : Form { const string connectionString2 = @"Data Source=MyDatabase;Password=xxxxxx;"; public Form1() { InitializeComponent(); } // Some code between... private void button_ShowUsers_Click(object sender, EventArgs e) //code that shows users in listBox { var dt = new DataTable(); using (var cn = new SqlCeConnection(connectionString2)) using (var cmd = new SqlCeCommand("Select * From Users", cn)) { cn.Open(); using (var reader = cmd.ExecuteReader()) { dt.Load(reader); var results = (from row in dt.AsEnumerable() select new { //UserID = row.Field&lt;int&gt;("ID"), FirstName = row.Field&lt;string&gt;("Firsname"), LastName = row.Field&lt;string&gt;("Lastname"), FullName = row.Field&lt;string&gt;("Firstname") + " " + row.Field&lt;string&gt;("Lastname") }).ToList(); listBox_users.DataSource = results; listBox_users.DisplayMember = "FullName"; } } } //I made an event for the listBox_users: private void listBox_users_SelectedIndexChanged(object sender, EventArgs e) //event code that should show listbox selected data in the textBoxes { if (listBox_inimesed.SelectedItem != null) { using (var cn = new SqlCeConnection(connectionString2)) using (var cmd = new SqlCeCommand("Select * From Users", cn)) { cn.Open(); using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { textBox1_firstname.Text = reader.GetString(1); textBox2_lastname.Text = reader.GetString(2); textBox3_email.Text = reader.GetString(3); textBox4_address.Text = reader.GetString(4); dateTimePicker1.Value = reader.GetDateTime(5); richTextBox_info.Text = reader.GetString(6); } else MessageBox.Show("Object not found"); } } } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload