Parth Doshi
Parth Doshi

Reputation: 4208

SQL Query to get a boolean value from a BIT type column

I am facing a problem getting the boolean value from one of the columns of my database. I am using SQL Server 2008 where in I have created a databaseas follows:

Table name: SysUser3 and columns as:

ProductName || ProductId || SelectedProducts

The column SelectedProducts is a BIT type column and contains False values for each of the row entries at present.

Now, I am writing a SQL Query to get the boolean value from my 'SelectedProducts' column

Here is my code:

    using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Database.mdf;User Instance=true"))
        {
            con.Open();

            string cmdString = "SELECT ProductName,SelectedProducts FROM SysUser3";
            using (SqlCommand cmd = new SqlCommand(cmdString, con))
            {
                using (SqlDataReader dataRead = cmd.ExecuteReader())
                {
                    while (dataRead.Read())
                    {
                        items.Add(new ProductModel
                        {
                            Selected=(bool)dataRead["SelectedProducts"];
                            ProductName= dataRead["ProductName"].ToString()
                        });
                    }
                }
            }
        }

I am getting an error at this line and hence not able to run the code:

Selected=(bool)dataRead["SelectedProducts"];

Am I doing it correctly ? can someone tell me what's wrong in the code?

Upvotes: 1

Views: 9554

Answers (2)

Nick VanderPyle
Nick VanderPyle

Reputation: 2999

You have a semicolon misplaced. Change it to a comma. It should read:

                while (dataRead.Read())
                {
                    items.Add(new ProductModel()
                    {
                        Selected=(bool)dataRead["SelectedProducts"],
                        ProductName= dataRead["ProductName"].ToString()
                    });
                }

Upvotes: 3

KV Prajapati
KV Prajapati

Reputation: 94645

You may try GetBoolean(column_odrinal) method.

  if(!dataRead.IsDBNull(1))
     Selected=dataRead.GetBoolean(1);

OR you may fix it if return value if null.

Selected =  (dataRead["SelectedProducts"] as bool?) ??  false ;

Upvotes: 3

Related Questions