Click here to Skip to main content
15,916,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get error on this code

An SqlParameter with ParameterName '@Main' is not contained by this SqlParameterCollection.

C#
SqlCommand command = new SqlCommand("SELECT * from Variables  WHERE ID = @ID", cs);
            command.Parameters.Add("@ID", SqlDbType.Int);
            command.Parameters["@ID"].Value = Main.pattern3.Text;

            
            cs.Open();

            command.ExecuteNonQuery();
            cs.Close();
            
            main = command.Parameters["@Main"].Value.ToString();
            amenu = command.Parameters["@Data"].Value.ToString();
            amenu1 = command.Parameters["@DataDetails"].Value.ToString();


main, amenu, and amenu1 are strings

anyone
Posted
Updated 13-Aug-13 1:22am
v3
Comments
[no name] 13-Aug-13 7:43am    
Are you expecting your query to return data in a parameter that does not exist?
Status BreakPoint 13-Aug-13 7:46am    
Because the query doesn't have Main and other parameters except @id.
shonezi 13-Aug-13 7:56am    
obviously I am stupid. that's why I posted here my problem, I am trying to get @Main, @Data, and @DataDetails values to those strings up there
[no name] 13-Aug-13 8:19am    
No one said you were "stupid". The error message is clear, you cannot use parameters that do not exist. What is not clear is what exactly is it that you are trying to do because this code makes no sense.
shonezi 13-Aug-13 8:27am    
I am sorry, this is what I am trying to do, I have table variables in Sql Server, with columns Main, Data and DataDetails

I want to get values from those columns by specific ID in strings on my form. I dont want to bind textboxes to it but I want to in sort of speak bind them with strings, and I dont know what to do

1 solution

The example you are showing is trying to use Output Parameters. Unfortunately, using a select everything query, this isn't doable. What you need to do is fill a DataTable and get the values out of it.

using(SqlConnection connection = new SqlConnection(_connectionString))
{
	SqlCommand command =
		new SqlCommand("SELECT * from Variables  WHERE ID = @ID", connection);
		
	command.Parameters.Add("@ID", SqlDbType.Int);
	command.Parameters["@ID"].Value = Main.pattern3.Text;
	
	SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
	
	DataTable dataTable;
	
	dataAdapter.Fill(dataTable);
	
	main = (String)dataTable.Rows[0]["Main"];
	amenu = (String)dataTable.Rows[0]["Data"];
	amenu1 = (String)dataTable.Rows[0]["DataDetails"];
}


If you wanted to stick with output parameters, you would need to switch your SQL statement to a stored procedure.
 
Share this answer
 
v2
Comments
shonezi 15-Aug-13 4:03am    
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900