There should be no difference in how Kentico handles the OnSelectionChanged event when set in Code-Behind or via the form. However, the Kentico Web Part lifecycle is slightly different to the ASP.Net Page Lifecycle.
I believe that your issue is being cause by the fact the OnContentLoaded event is firing before the OnSelectionChanged event and hence you are actually recreating the 'catgories' dropdown which in turn removes the selected value.
I haven't tested this but the below should work:
public override void OnContentLoaded()
{
base.OnContentLoaded();
if (!IsPostBack)
{
InitializeCategories();
}
// THIS IS WHERE I NEED TO GET THE SELECTED VALUE OF CATEGORY
// I'VE TRIED THIS
if (IsPostBack)
{
int categoryId = Int32.Parse(category.SelectedValue); // This doesn't seem to work
DataSet partsResult = new DataQuery("Custom.Parts.selectall")
.Columns("partId", "partName")
.Where("categoryId", QueryOperator.Equals, categoryId)
.Execute();
DataTable parts = partsResult.Tables[0];
if (parts.Rows.Count > 0)
{
part.DataSource = parts;
part.DataTextField = "partName";
part.DataValueField = "partId";
part.DataBind();
}
}
}
private void InitializeCategories()
{
DataSet categoryResult = new DataQuery("Custom.CategoriesTable.selectall")
.Columns("CategoryId", "CategoryName")
.Execute();
DataTable categories = categoryResult.Tables[0];
if (this.categories.Rows.Count > 0)
{
category.DataSource = countries;
category.DataTextField = "CategoryName";
category.DataValueField = "CategoryId";
category.DataBind();
}
}