how are you doing? I tell you, I am making a system in visual studio with windows form in C# and I wanted to make a "Query" class to put the queries to the database. I get complicated here when I have to fill a listbox. It occurred to me to pass by reference to the function Consulta_BuscarCalle (which belongs to the Query class). I make the call from the form called RegistrarCliente and I would pass the listbox that belongs to this form as parameters. My code is this:
private void BuscarCalleRegCliente()
{
lsbxCallesRegCliente.Items.Clear();
MySqlConnection conex = ConexionBD.conexionDevuelve();
conex.Open();
string query = "Select nomCalle from calles where nomCalle like'%" + txtNomCalleRegCliente.Text + "%'";
using (MySqlCommand com = new MySqlCommand(query, conex))
{
using (MySqlDataReader red = com.ExecuteReader())
{
while (red.Read())
{
lsbxCallesRegCliente.Items.Add(red[0].ToString());
}
red.Close();
}
}
}
How do I put all that code in the Consult_BuscarCalle function and pass it a parameter by reference to the listbox called lsbxCallesRegCliente to fill it from the same function? Thank you very much, greetings!
I did everything as you put me, the issue is that it is not doing a part of the code. I show you:
The function was like this:
public static List<string> BuscarCalle(string nombre)
{
List<string> listCalles = new List<string>();
MySqlConnection conex = ConexionBD.conexionDevuelve();
conex.Open();
string query = "Select nomCalle from calles where nomCalle like'% + ?nombre + %'";
using (MySqlCommand com = new MySqlCommand(query, conex))
{
com.Parameters.AddWithValue("?nombre", nombre);
using (MySqlDataReader red = com.ExecuteReader())
{
while (red.Read())
{
listCalles.Add(red[0].ToString());
}
red.Close();
}
}
return listCalles;
}
The using that the datareader has does not pass it, as it skips it. And it doesn't bring me any data. What did I do wrong?
Edit: I solved it by changing the name to @name and changing what's inside the Parameters.AddWithValue. It remained like this:
public static List<string> BuscarCalle(string nombre)
{
List<string> listCalles = new List<string>();
MySqlConnection conex = ConexionBD.conexionDevuelve();
conex.Open();
string query = "Select nomCalle from calles where nomCalle like @nombre";
using (MySqlCommand com = new MySqlCommand(query, conex))
{
MessageBox.Show("primer using");
com.Parameters.AddWithValue("@nombre", "%"+ nombre+"%");
using (MySqlDataReader red = com.ExecuteReader())
{
MessageBox.Show("lee el read");
if (red.Read())
{
MessageBox.Show("dentro del while");
listCalles.Add(red[0].ToString());
}
else
{
MessageBox.Show("No lee");
}
}
}
return listCalles;
}
You don't have to pass any component
listBox
to that function, because it shouldn't be its responsibility to load it, it should just return the data, like:and then from the UI access the control to assign the data