What's Wrong with These Parameters

Parameters not working, what's wrong here

You have a scope issue. You define the SqlCommand com outside of the scope where you modify it (ie- add to the parameters list). Essentially you are adding the @name parameter each time your btnSave_Click method is called.

Move the line where you create com into the method so it looks like this:

 SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "insert into Table_1 values ( @name ,@location )";
com.Parameters.AddWithValue("@name", txtName.Text);
com.Parameters.AddWithValue("@location", txtLocation.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();

And remove SqlCommand com = new SqlCommand(); from the top of the code.

This way the command gets recreated every time the method runs, and when it gets recreated the parameters list will be empty and the lines where you add the parameters won't fail.

EDIT
To further clarify - The issue is that when you define it where you do, then you only should add the parameters once. As a "global variable" (actually, in your code it's called a field) such as you're creating it only gets instantiated once, which is fine. The problem arises when you add parameters to the SqlCommand. Because that button click handler runs each time (I assume) a button is clicked you are repeatedly adding the parameters to the list. The first time you click the button is ok, because the parameters list is empty at that time. The next time you click the button you will get the exception because that list already has those parameters added.

If you want to continue to use cmd as a global variable / field then you should clear the parameters list in your handler method like this:

 com.Connection = con;
com.CommandText = "insert into Table_1 values ( @name ,@location )";
com.Parameters.clear();
com.Parameters.AddWithValue("@name", txtName.Text);
com.Parameters.AddWithValue("@location", txtLocation.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();

What's wrong with these macro parameters?

Macro variables do not use quotations.

%macro test(var);

%if &var = %str(Sub Prime) %then %do;
%let var2 = Sub_Prime;
%put &=var2;
%end;
%mend;

%test(Sub%str( )Prime);

You'd be better off using %str around the whole thing, though, rather than inserting the %str in just the space.

%test(%str(Sub Prime));

whats wrong with the default parameters?

Mention the default value for the parameter in the declaration ONLY:

//declaration  with default parameter
void loadFromFile( string const& fileName,
Frames& frames,
ostream& log =std::clog);

Don't mention the default value in the definition:

//definition
void loadFromFile( string const& fileName,
Frames& frames,
ostream& log)
{
//....
}

Now its perfect. It should compile now!



Related Topics



Leave a reply



Submit