1

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?

1
  • The error message suggests that there are "syntax errors" on that very line that I have mentioned above plus the following line of ProductName=.... Commented Dec 24, 2011 at 5:07

2 Answers 2

3

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()
                    });
                }
Sign up to request clarification or add additional context in comments.

Comments

3

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 ;

1 Comment

In this case, you know the ordinal position of the column is 1, but if you wanted to get it by column name, use GetOrdinal(). msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.