Tom Gullen
Tom Gullen

Reputation: 61755

ASP.net c# simple query paramter question

        // Add into DB
        using (tblArtworkTemplatesTableAdapter tblAdapter = new tblArtworkTemplatesTableAdapter())
        {
            tblAdapter.Insert(DateTime.Now, "@specID");
            "@specID" = int.Parse(lstChooseSpec.SelectedValue)
        }

I know the code is wrong, just for illustration of my objective, how do I paramatise the input?

Upvotes: 0

Views: 346

Answers (2)

luckyluke
luckyluke

Reputation: 1563

Generally it depends. If You are using any kind of ORM like LINQ to SQL or NHibernate, it will do it for You no questions asked. If YOu are doing it using Plain ADO objects (which I suppose is the case) then You will have to comeup with the Command (or SQLCommand or any other ICommand implementation) object and use SQLParameter class (or other parameter classes).

ICommand has the collection of parameters that You can arbitralily edit.

    SqlCommand cmd = new SqlCommand(
            "select * from STH where column = @SpecID", conn);

    //it might be useful to specify a type as well
    SqlParameter param  = new SqlParameter();
    param.ParameterName = "@SpecID";
    //I woudl use the TryParse method though
    param.Value         = int.Parse(lstChooseSpec.SelectedValue);

    cmd.Parameters.Add(param);

Upvotes: 2

3Dave
3Dave

Reputation: 29051

This line

"@specID" = int.Parse(lstChooseSpec.SelectedValue)

Is incorrect. You can't assign a value to a constant. You might mean something like

specId = int.Parse(lstChooseSpec.SelectedValue);

The rest of the code is confusing. Why are you parsing lstChooseSpec.SelectedValue to an integer, then trying to add it to the adapter as a DateTime? C# is strongly-typed: something is either an int or a DateTime, but cannot be both.

It might help if you could post the rest of the method.

Also, have a look at this overview on MSDN.

Upvotes: 1

Related Questions