Dave
Dave

Reputation: 159

Adding parameters to Select query in Code behind

I want to fill a GridView with data from a database and let the user choose what part of the "Cursussen" Table is shown. He can do this by changing the selection of the parameter in a dropdownbox.

Error : No overload for method "Add" takes 2 arguments.

protected void Page_Load(object sender, EventArgs e)
{
    ConnectionStringSettings planner =
        ConfigurationManager.ConnectionStrings["CursusDatabase"];
    DbConnection connection = new SqlConnection(planner.ConnectionString);
    DbCommand cmd = connection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "SELECT * FROM Cursussen " +
        "WHERE CursusId = @CursusId";
    cmd.Parameters.Add("CursusId", DropDownList1.SelectedValue); // <-- here

    connection.Open();
    DbDataReader rdr = cmd.ExecuteReader();
    DataTable planning = new DataTable();
    planning.Load(rdr);
    connection.Close();

    GridView1.DataSource = planning;
    GridView1.DataBind();
    }
}

Upvotes: 0

Views: 2645

Answers (3)

Ryan McDonough
Ryan McDonough

Reputation: 10012

Dim myParamList As New List(Of SqlParameter)()
Dim myParam As SqlParameter = Nothing

myParam = New SqlParameter("@X", SqlDbType.Int)
myParam.Value = Y
myParamList.Add(myParam)

Then add the parameter list to the command.

Upvotes: 0

Oded
Oded

Reputation: 499392

You are using DbCommand - if you change this to be SqlCommand, you can do the following:

cmd.Parameters.AddWithValue("CursusId", DropDownList1.SelectedValue);

Otherwise, you need to use the Add method that takes a DbParameter:

cmd.Parameters.Add(new DbParameter { ParameterName = "CursusId", 
                                     Value = DropDownList1.SelectedValue});

Upvotes: 0

Habib
Habib

Reputation: 223422

EDIT:

As specified by Oded in the comments, I missed that you are using DbCommand

var parameter = cmd.CreateParameter();
parameter.ParameterName = "CursusId";
parameter.Value = DropDownList1.SelectedValue;
cmd.Parameters.Add(parameter);

Upvotes: 5

Related Questions