Showing posts with label methods. Show all posts
Showing posts with label methods. Show all posts

Must declare the scalar variable @variableName c# Sql


When u need to pass parameters to sql Query. This can be done in two ways..

First one:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

string query = "select * from table where columnName = '" + txtSearch.Text + "'";

SqlCommandcommand = new SqlCommand(query,connection);

Bur this approach is not recommended. this may lead to error sometimes. So, whenever we need to pass parameters to query, use SqlParamater. The same query can be written as..

string query = "select * from table where columnName =@value";

SqlCommand command = new SqlCommand(query,connection);

command.Parameters.AddWithValue("@value",txtSearch.Text);

Using SqlParameters gives a cleaner, less error prone and SQL injection safe (comparative) code.


Read more...

Return only one result from LINQ Query

You can do it in two ways, either use First or use Single.

First returns only first row, even there are multiple rows

Single expects only one row to be returned, and if there are multiple rows, it throws exception.

So, use Single if you are expecting only one row to be returned.

EX: var book= from book in store where (book.price > 100) select book).First();
Generally , the query returns all books having price greater than 100. but , as we are using  " .First() " only first book will be returned.


Read more...

return more than one value from a method


We can't return more than one values from a method.

An alternative way would be, add all those values to be returned into  Array and return that array.

Ex: public int[] returnArray ()
{
int[] myArray=new int[3];
myArray[0] = value1;
myArray[1] = value2;
myArray[2] = value3;

      return myArray;
}

Read more...