简体   繁体   中英

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 = )

类别表在这里

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

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);

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.

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

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM