4

How can i set sql parameters for an sqlDatasource in the code behind? I am trying like this:

int id=1;
SqlDataSource1.SelectCommand = "SELECT * FROM categ WHERE id=@id";
SqlDataSourceArticole.SelectParameters.Add("@id", id);
// and also like this:
SqlDataSourceArticole.SelectParameters.Add("id", id);

but it doesn't work? What am i doing wrong?

hhh3112
  • 2,167
  • 10
  • 36
  • 55

2 Answers2

5

Make sure you add the select parameters before trying to set their default value.

i.e.

SqlDataSourceArticole.SelectParameters.Add("@id", id);
SqlDataSourceArticole.SelectParameters["id"].DefaultValue = id.ToString();
darth_phoenixx
  • 932
  • 12
  • 23
2

You can update the value by:

SqlDataSourceArticole.SelectParameters["id"].DefaultValue = id.ToString();

Using the default value can work in this case.

HTH.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • i get 'System.NullReferenceException: Object reference not set to an instance of an object.' – hhh3112 Feb 09 '11 at 19:40
  • The ID parameter has to exist in markup; if you are programmably create the collection of parameters, then when you create the parameter, also set the default value. – Brian Mains Feb 10 '11 at 17:04