Shqiptar
Shqiptar

Reputation: 65

How to select subcategory in asp.net

I can get main categories with this query:

DataTable dtCategory = system.GetDataTable("Select * from TBLCATEGORIES");

But I want to get subcategories so I'm trying this query:

DataTable dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID="+CategoryID);

But I got error with this.. pls help.

Incorrect syntax near '='. (Select * from TBLCATEGORIES where SubCategoryID = ) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Exception: Incorrect syntax near '='. (Select * from TBLCATEGORIES where SubCategoryID = )

categories table is here

private void BindRepeater()
{
    DataTable dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID="+CategoryID);
    if (dtCategory.Rows.Count > 0)
    {
        rpCategory.DataSource = dtCategory;
        rpCategory.DataBind();
    }
}

Upvotes: 0

Views: 85

Answers (3)

Anwar Ul-haq
Anwar Ul-haq

Reputation: 1881

Not sure what's your system.GetDataTable method does. Try this.

           DataTable dtCategory = new DataTable();

            int CategoryID = 0;
            SqlConnection conn = new SqlConnection(connectionString);
            string query = "Select * from TBLCATEGORIES where SubCategoryID = " + CategoryID;

            SqlCommand cmd = new SqlCommand(query, conn);

            using (SqlDataAdapter a = new SqlDataAdapter(cmd))
            {
                a.Fill(dtCategory);
            }

            foreach (var subCategories  in dtCategory.Rows)
            {

                   // your logic goes here

            }

Upvotes: 0

Krishna Kumar N
Krishna Kumar N

Reputation: 135

Can you please let us know what is the type of CategoryID? If it is a string, then the check would be something like this;

if (string.IsNullOrEmpty(CategoryID))
  dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID IS NULL");
else
  dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID="+CategoryID);

If this doesn't help then please provide us more information on CategoryID to help you resolve this error.

Upvotes: 0

diiN__________
diiN__________

Reputation: 7656

You need to check if CategoryID is null before building the query:

DataTable dtCategory;

if (CategoryID != null)    
    dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID="+CategoryID);
else
    dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID IS NULL);

Upvotes: 1

Related Questions