2

can you help me with this? I really can't undertand how to do it.

What I'm trying to do, is that when I give it an id, compare it with another id stored in the database.

public Rubro GetRubroById(int GivenId)
{

    Rubro rubro = new Rubro();
    SqlCommand command = new SqlCommand

    ("SELECT * FROM Rubro WHERE GivenId = Id", con);
    try
    {
        con.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            rubro.Id = reader.GetInt32(0);
            rubro.Name = reader.GetString(1);
        }
        con.Close();
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }

    return rubro;
}
Bassie
  • 9,529
  • 8
  • 68
  • 159

2 Answers2

1

You have to pass the value to the sql query parameter:

using(var command = new SqlCommand("SELECT * FROM Rubro WHERE Id = @GivenId", con))
{
    try
    {
        command.Parameters.Add("@GivenId", SqlDbType.Int).Value = GivenId;
        con.Open();
        using(var reader = command.ExecuteReader())
        while (reader.Read())
        {
            rubro.Id = reader.GetInt32(0);
            rubro.Name = reader.GetString(1);
        }
        con.Close();
    }
    catch (SqlException ex)
    {
       MessageBox.Show(ex.Message);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

The problem is that GivenId variable in the SQL that you pass has no relationship to GivenId variable of GetRubroById method. Despite their common name, the two exist in different parts of the system.

You need to pass the value to the statement using parameters:

SqlCommand command = new SqlCommand("SELECT * FROM Rubro WHERE @GivenId = Id", con);
command.Parameters.Add("@GivenId", SqlDbType.Int);
command.Parameters["@GivenId"].Value = GivenId; // rename to givenId

You should rename GivenId to givenId in compliance with .NET naming conventions.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523