liza person
liza person

Reputation: 11

Using Winforms to connect to SQL Server to easily filter data

I have a Winforms that is connecting to a SQL Server 2008 database.

I would like to be able to easily filter through data in one table.

Here is an example of what I would like:

Is there already an easy solution for this?

Upvotes: 1

Views: 2630

Answers (2)

jhenriquez
jhenriquez

Reputation: 180

I don't think there is a yet unique way of doing this. Anyways, you can simply use a SqlCommand it will allow you to execute a storedprocedure or a query as you like. The you pass the three filter values as SqlParameters.

Here is a little example:

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT * FROM MyTable Where (FieldOne == @ParameterOne Or FieldTwo = @ParameterTwo Or FieldThree = @ParameterThree)";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        // Create the command
        SqlCommand command = new SqlCommand(
            queryString, connection);
        // Add the parameters

        command.Parameters.Add(new SqlParameter("ParameterOne", txtMyTextBox1.Text));
        command.Parameters.Add(new SqlParameter("ParameterTwo", txtMyTextBox2.Text));
        command.Parameters.Add(new SqlParameter("ParameterThree", txtMyTextBox3.Text));
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

Then you use the SqlDataReader to get the values.

Upvotes: 2

Related Questions