Showing posts with label categories. Show all posts
Showing posts with label categories. Show all posts

Monday, March 26, 2012

CasdadingDropDown with Db in VB.net

Well I have tried to follow the example in c# and a great post using access. I am trying to populate the first dropdown with Activity categories from a SQL database called PA. I created a dataset with two difference datatables in it: One for populating the first with a distinct clause: Select Distring [Category] FROM [Compendium] SORT asc. The second ta with a Select Command of "Select [CaseCode], [Mets], [Description], [Category] Where [Category = @dotnet.itags.org.Category]

I set the CasdadingDropDown Properties as follows:

 <cc1:CascadingDropDown ID="CascadingDropDown1" runat="server"> <cc1:CascadingDropDownProperties TargetControlID="ddActCat" ServiceMethod="GetActCat" ServicePath="ActType.asmx" PromptText="Choose an Activity Category" Category="Cat" /> <cc1:CascadingDropDownProperties TargetControlID="ddCatType" ServicePath="ActType.asmx" ServiceMethod="GetActType" PromptText="Choose Activity Type" ParentControlID="ddActCat" Category="Type" /> </cc1:CascadingDropDown>
 
The asmx file ActType.asmx:
 
<%@dotnet.itags.org. WebService Language="VB"Class="ActType" %>Imports System.WebImports System.Web.ServicesImports System.Web.Services.ProtocolsImports AtlasControlToolkitImports System.Collections.GenericImports System.DataImports System.Data.SqlClient<WebService(Namespace :="http://tempuri.org/")> _<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _Public Class ActTypeInherits System.Web.Services.WebService <WebMethod()> _Public Function GetActCat(ByVal knownCategoryValuesAs String,ByVal categoryAs String)As AtlasControlToolkit.CascadingDropDownNameValue()Dim actAs New ActivityTableAdapters.ActivityCateogry_TblTableAdapter()Dim ActCatAs Activity.ActivityCateogry_TblDataTable = act.GetActCat()With ActCatDim intRowAs Integer Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)For intRow = 0To .Rows.Count - 1 values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(0).ToString, .Rows(intRow).ItemArray(0)))Next Return values.ToArrayEnd With Return New CascadingDropDownNameValue() {}End Function <WebMethod()> _Public Function GetActType(ByVal knownCategoryValuesAs String,ByVal categoryAs String)As CascadingDropDownNameValue()Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)Dim CompCodeAs Integer If (kv.ContainsKey("Cat")And Int32.TryParse(kv("Cat"), CompCode))Then Dim taAs New ActivityTableAdapters.ActivityType_TblTableAdapter()Dim ActTypeAs Activity.ActivityType_TblDataTable = ta.GetType(CompCode)With ActTypeDim intRowAs Integer Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)For intRow = 0To .Rows.Count - 1 values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(3).ToString, .Rows(intRow).ItemArray(2)))Next Return values.ToArrayEnd With End If Return New CascadingDropDownNameValue() {}End Function End Class

The first dropDown name ddActCat populates fine, but the second does not. Also these dd's are in an updatePanel control and the Cdd Extender is outside the Updatepanel. I have tried it both ways. I need to have it inside the UpdatePanel becuase it is in line with other controls in a form. Should I seperate the others into two UpdatePanels and have the CDD outside?

I am really not sure what is going on in the second WebMethod GetType() please help.

I finally got the code to work after checking the WebService paths and making some minor adjustments to the table Items(Count). Here is my asmx file code that worked with SQL DataSet.

<%@. WebService Language="VB"Class="ActType" %>Imports System.WebImports System.Web.ServicesImports System.Web.Services.ProtocolsImports AtlasControlToolkitImports System.Collections.GenericImports System.DataImports System.Data.SqlClient<WebService(Namespace :="http://tempuri.org/")> _<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _Public Class ActTypeInherits System.Web.Services.WebService <WebMethod()> _Public Function GetActCat(ByVal knownCategoryValuesAs String,ByVal categoryAs String)As AtlasControlToolkit.CascadingDropDownNameValue()Dim actAs New ActivityTableAdapters.ActivityCategory_TblTableAdapter()Dim ActCatAs Activity.ActivityCategory_TblDataTable = act.GetActCat()With ActCatDim intRowAs Integer Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)For intRow = 0To .Rows.Count - 1 values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1).ToString, .Rows(intRow).ItemArray(0)))Next Return values.ToArrayEnd With Return New CascadingDropDownNameValue() {}End Function <WebMethod()> _Public Function GetActType(ByVal knownCategoryValuesAs String,ByVal categoryAs String)As CascadingDropDownNameValue()Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)Dim CatIDAs Integer If (kv.ContainsKey("Category")And Int32.TryParse(kv("Category"), CatID))Then Dim taAs New ActivityTableAdapters.ActivityType_TblTableAdapter()Dim ActTypeAs Activity.ActivityType_TblDataTable = ta.GetType(CatID)With ActTypeDim intRowAs Integer Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)For intRow = 0To .Rows.Count - 1 values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(2).ToString, .Rows(intRow).ItemArray(1)))Next Return values.ToArray()End With End If Return New CascadingDropDownNameValue() {}End Function End Class

Most of the code came fromt converting the Example from the Toolkit and from post:

http://forums.asp.net/1362555/ShowThread.aspx#1362555

ThanksAthertonCreative is not online. Last active: 08-06-2006, 10:42 AMAthertonCreative you were very helpful with your post.

T


One problem I am having is that when I click on the second dd the wrong entry fills the dd text value. The Value of the dd is not the text value and is not unique, could it be looking to place the value in the dd instead of the text? By the By, I tried to do this with two dd's and a SQLDataSource with an Update panel. It worked, and had the same error. Help!!!


Maybe double-check that the order of the parameters to the CascadingDropDownNameValue constructor are correct? The correct order is: name, value.
Thanks for the reply dave. The dataset that gets returned has several values in the query. The first column is the ID, second is Mets, third is Description or Type of Activity, and fourth is CategoryID or (0,1,2,3). So I chose 2 for the Name and 1 for the Value. I want the Activity Type displayed as text and the Value to be the METS so I can calculate calories burnt more precisely. I checked and I have the pair set correctly. I also checked by not using a CDD but with two dd's from sqlDataSource and same problem. I have seen this issue before. When a large number of choice populate a DD then sometimes the wrong value appears when selected. I think it looks for the SelectedValue which is the same as the Item selected and choice the first one it comes to.
I think I can see how that might happen if you have multiple values that are the same. But I wouldn't think it would be a problem if you have multiple names that are the same. If you're seeing this without using CascadingDropDown at all, then it's probably pretty safe to say it's not responsible, but it might be interesting to get to the bottom of this anyway. :)

Well at least in this case I have to change my Cascading Drop downs anyway because I cannot get at the values and the needed selectedItem.Text value, which makes no sense to me what so ever. I would think since you have to use name-value pairs to retrieve the cdd's then you would want to be able to retrieve the SelectedItem.Text value somehow to write it back somewhere.

Write now I have to use the SelectedValue to get the ID of the item I want and make another DB call to get that value AGAIN, seems a waste.

Any help on either front would be great!


I was going to point you athttp://forums.asp.net/thread/1317472.aspx for some more information, but it looks like you're already part of that thread. :)

Dave: Thanks for your input, and I always search the posts prior to posting. I have learned many things that way.

One issue was that I had the DD's in post back mode from trying to use the sqldatasource without altas. after removing the property it works better now, but still has some hickups when alot of data populated the dd's. Not as many errors but still a few.

I also HATE the fact that we cannot get at the selectedItem.text value. This is a pain.


FYI, I've opened work item 1895 to track the .Text request.

Wednesday, March 21, 2012

CascadingDropDown questions

I have 2 DropDownLists. One for categories and the other one for subcategories. When I change a category I want the subcategories to change. I thought this could be accomplished using the CascadingDropDown extender but I'm facing some problems.

I have populated (in the Page_Load method) both dropdownlists but the web service gets called to populate the dropdownlists. Is there any way to make the extender only call the webservice when the selection changes if it's populated with data?

Another question is why the webservice is called 3 times at start up, one for the categories (knownCategoryValues = "", category = "categories"), and two for the subcategories (knownCategoryValues = "categories:", category = "subcategories" and knownCategoryValues = "categories:1", category = "subcategories").

I thought it would be called twice not three times.

BTW, there is a helper method to return values using an xml document:

AtlasControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument

please add something similar to extract values from a DataTable.

Thanks.

The short answer is that we need to do some optimization around how many times the webservice is called. It's currently called three times because:

1) Once to populate the first list

2) Once to populate the second list

3) Once when the second list detects the value of the first list has changed

So there's some work do be done, and what you're seeing is an early version. In any case, you should apply some caching to your web service to improve performance (seehttp://support.microsoft.com/?scid=kb;en-us;318299).


Thanks for the reply Shawn but my main problem was this:

I have populated (in the Page_Load method) both dropdownlists but the web service gets called after to populate again the dropdownlists.

Is there any way to make the extenderonlycall the webservice when the selection changes if the dropdownlist is already populated with data?

And now that you have mentioned caching the web service. I was already caching my web service but I was wondering if Atlas does some kind of client caching when calling a web service if the web service is cached?

Thanks,
Manu


Yeah - the fix in the toolkit is pretty easy. Open CascadingDropDownBehavior.js, and find the "_onParentChange" method. Replace it with this:

var _lastParentValues;this._onParentChange = function() { var e =this.control.element;// Create the known category/value pairs string for sending to the helper web service // Follow parent pointers so that the complete state can be sent // Format: 'name1:value1;name2:value2;...' var knownCategoryValues =''; var parentControlID = _parentControlID;while (parentControlID) { var parentElement = document.getElementById(parentControlID);if (parentElement && (-1 != _parentElement.selectedIndex)) { knownCategoryValues = parentElement.CascadingDropDownCategory +':' + parentElement.options[parentElement.selectedIndex].value +';' + knownCategoryValues; parentControlID = parentElement.CascadingDropDownParentControlID; }else { parentControlID =null; } }if (knownCategoryValues !='' && _lastParentValues == knownCategoryValues) {return; } _lastParentValues = knownCategoryValues;// Call the helper web service Sys.Net.ServiceMethod.invoke( _servicePath, _serviceMethod,null, {'knownCategoryValues' : knownCategoryValues,'category' : _category }, Function.createDelegate(this, _onMethodComplete), Function.createDelegate(this, _onMethodTimeout), Function.createDelegate(this, _onMethodError), Function.createDelegate(this, _onMethodAborted),this ); }

It is not working Shawn.

I have made a simple example so you can test it yourself quickly:

---- BEGIN Example.aspx ---

<%@.PageLanguage="C#"AutoEventWireup="true"CodeFile="Example.aspx.cs"Inherits="Example"%>

<%@.RegisterAssembly="AtlasControlToolkit"Namespace="AtlasControlToolkit"TagPrefix="cc1"%>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<cc1:cascadingdropdownid="CascadingDropDown1"runat="server">

<cc1:CascadingDropDownPropertiesTargetControlID="ddlCategorias"Category="categorias"ServiceMethod="GetCategorias"ServicePath="Example.asmx"/>

<cc1:CascadingDropDownPropertiesTargetControlID="ddlSubcategorias"Category="subcategorias"ServiceMethod="GetSubcategorias"ServicePath="Example.asmx"ParentControlID="ddlCategorias"/>

</cc1:cascadingdropdown>

</div>

<atlas:ScriptManagerID="ScriptManager1"runat="server">

</atlas:ScriptManager>

<asp:DropDownListID="ddlCategorias"runat="server"DataTextField="Nombre"DataValueField="IdCat">

</asp:DropDownList>

<asp:DropDownListID="ddlSubcategorias"runat="server"DataTextField="Nombre"DataValueField="IdCat">

</asp:DropDownList>

</form>

</body>

</html>

---- END Example.aspx ---


---- BEGIN Example.aspx.cs ---

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

publicpartialclassExample : System.Web.UI.Page

{

protectedvoid Page_Load(object sender,EventArgs e)

{

ddlCategorias.DataSource = GetCategoriasPrimerNivel();

ddlCategorias.DataBind();

ddlCategorias.SelectedValue ="1";

ddlSubcategorias.DataSource = GetSubcategorias(1);

ddlSubcategorias.DataBind();

ddlSubcategorias.SelectedValue ="10";

}

privateCategoria[] GetCategoriasPrimerNivel()

{

Categoria[] categorias =newCategoria[5];

for (int i = 0; i < categorias.Length; i++) {

categorias[i] =newCategoria(i,"CAT " + i);

}

return categorias;

}

privateCategoria[] GetSubcategorias(int p)

{

Categoria[] subcategorias =newCategoria[10];

for (int i = 0; i < subcategorias.Length; i++) {

subcategorias[i] =newCategoria(i + 5,"SUBCAT (" + p +", " + i +")");

}

return subcategorias;

}

}

---- END Example.aspx.cs ---

---- BEGIN Example.asmx ---

<%

@.WebServiceLanguage="C#"CodeBehind="~/App_Code/Example.cs"Class="Example" %>

---- END Example.asmx ---

---- BEGIN Example.cs ---

using System;

using System.Web;

using System.Collections;

using System.Collections.Specialized;

using System.Web.Services;

using System.Web.Services.Protocols;

///<summary>

/// Summary description for Example

///</summary>

[WebService(Namespace ="http://tempuri.org/")]

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

publicclassExample : System.Web.Services.WebService {

public Example () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod]

public AtlasControlToolkit.CascadingDropDownNameValue[] GetCategorias(string knownCategoryValues,string category)

{

// Get a dictionary of known category/value pairs

StringDictionary knownCategoryValuesDictionary = AtlasControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

Categoria[] categorias = GetCategoriasPrimerNivel();

AtlasControlToolkit.CascadingDropDownNameValue[] returnValue =new AtlasControlToolkit.CascadingDropDownNameValue[categorias.Length];

for (int i = 0; i < categorias.Length; i++) {

returnValue[i] =new AtlasControlToolkit.CascadingDropDownNameValue("WS_" + categorias[i].Nombre, categorias[i].IdCat.ToString());

}

return returnValue;

}

[WebMethod]

public AtlasControlToolkit.CascadingDropDownNameValue[] GetSubcategorias(string knownCategoryValues,string category)

{

// Get a dictionary of known category/value pairs

StringDictionary knownCategoryValuesDictionary = AtlasControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

string str = knownCategoryValuesDictionary["categorias"];

Categoria[] subcategorias = GetSubcategorias(Int32.Parse(str));

AtlasControlToolkit.CascadingDropDownNameValue[] returnValue =new AtlasControlToolkit.CascadingDropDownNameValue[subcategorias.Length];

for (int i = 0; i < subcategorias.Length; i++) {

returnValue[i] =new AtlasControlToolkit.CascadingDropDownNameValue("WS_" + subcategorias[i].Nombre, subcategorias[i].IdCat.ToString());

}

return returnValue;

}

privateCategoria[] GetCategoriasPrimerNivel()

{

Categoria[] categorias =newCategoria[5];

for (int i = 0; i < categorias.Length; i++) {

categorias[i] =newCategoria(i,"CAT " + i);

}

return categorias;

}

privateCategoria[] GetSubcategorias(int p)

{

Categoria[] subcategorias =newCategoria[10];

for (int i = 0; i < subcategorias.Length; i++) {

subcategorias[i] =newCategoria(i + 5,"SUBCAT (" + p +", " + i +")");

}

return subcategorias;

}

}

---- END Example.cs ---

Note that I have bound both dropdownlists at Page_Load with values CAT XXX and SUBCAT XXX.

However when you run the sample you get WS_CAT XXX and WS_SUBCAT XXX that are the values returned by the web service.


Hi Manuel,

I think we've fixed the issue you're having with the latest version of the toolkit. I'd recommend you get that installed and see if it makes it work.

Thanks,
Ted