Question

Good day. How can i put a search in my program in c#? It would search record from SQL database then display the records in listview. thanks you

i've tried add this line of code in my program but an error message appears: There is already an open DataReader associated with this Command which must be closed first

private void button6_Click(object sender, EventArgs e)
{
    SqlConnection MySqlConnection;
    SqlDataReader m_dr;
    SqlCommand command;
    DataTable p_table = new DataTable();

    MySqlConnection = new SqlConnection("Data Source=A-A-PC\\MSSQLSERVER1;Initial Catalog=lights and sounds;User ID=sa;Password=itexpert;");

    MySqlConnection.Open();
    command = new SqlCommand("SELECT * FROM inventory  WHERE package='" + textBox7.Text + "'", MySqlConnection);
    m_dr = command.ExecuteReader();

    if (m_dr.HasRows)
    {
        SqlCommand command1 = new SqlCommand("Select * from inventory", MySqlConnection);
        p_table.Clear();
        SqlDataAdapter m_d = new SqlDataAdapter("Select * from inventory", MySqlConnection);

        m_d.Fill(p_table);
        listView1.Items.Clear();

        for (int i = 0; i < p_table.Rows.Count; i++)
        {
            DataRow drow = p_table.Rows[i];
            if (drow.RowState != DataRowState.Deleted)
            {
                ListViewItem lvi = new ListViewItem(drow["id"].ToString());
                lvi.SubItems.Add(drow["package"].ToString());
                lvi.SubItems.Add(drow["number"].ToString());
                listView1.Items.Add(lvi);
            }
        }
    }
}

No correct solution

OTHER TIPS

Here are some things that may be causing issues or conflicts. They may be unnecessary but it just neatens your code.

  1. Create the SQL Command object inside your SQL Connection:

    MySQLConnection = new SQLConnection(/*Connection string here*/);
    command = MySQLConnection.CreateCommand();
    
  2. Use a try{} catch{} block. This will catch on any errors and show you what is going on if you follow the code in debug mode. eg.

    try
    {
    //your code here
    }
    catch(SqlException e){ Console.WriteLine(e.Message); }
    finally
    { if (MySQLConnectrion != null)
        {
            MySQLConnection.Close();
        }
    }
    

Your code is lacking "using" block. Use the using block to make sure of the disposal of the connection. Like this:

using (SqlConnection sqlConn = new SqlConnection())
{
    conn.Open();
    Sqlmd.Connection = sqlConn;
    SqlDataAdapter da = new SqlDataAdapter(Sqlmd);
   //code goes here...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top