Showing posts with label cascadingdropdown. Show all posts
Showing posts with label cascadingdropdown. Show all posts

Wednesday, March 28, 2012

PostBack once all lists in CascadingDropDown are selected

Has anyone found a way to generate a postback once all lists in a CascadingDropDown have a valid selection.

I am converting a web app that has many places where the user has to select Software, Version, Terrain and Course (It's a Virtual Reality Cycling Portal) Previously each selection caused a postback to populate the next list. On each post back the state of the page may need to changed, in terms of different controls being visible to capture either the riders time or the distance they cover.

I have switched to using Atlas and created a UserControl with the CDD to reduce the postbacks, but I still need to change the state of the controls with a postback, as I need to lookup details of the course to determine which controls should be visible.

So what I need to do is generate a postback once all lists have a valid selection. As a last resort I can turn the Ride Upload tool I am referring to into a wizard, but I would prefer to keep the new UI similar to the original single form one users are already using.

The user control is working great in all but this one scenario, as the other scenarios all require the user to click on a button to trigger the update of a data control.

Once the last CDD gets a selection, you know that all the CDDs have a selection - might you be able to tag the last CDD with AutoPostBack? Alternatively, maybe you could write a little bit of JS to run on the client side and hook the onchange event of the DDL and do the postback manually?

Monday, March 26, 2012

Preselecting a value in the CascadingDropDown control

G'day,

I have a form that saves and loads data from a database. Creating new forms is fine however when reloading hthe form for editing I want the CascadingDropDown control to have its previously selected value displayed.

I have tried the obvious such as loading the controls data and using SelectedValue = someId but it didn't work (probably not surprising!). I also tried setting the controls Text property incase Atlas detected a non empty value and left it alone. I had a bit of a look at the source but I don't yet know enough about the architecture to answer the question myself or to write some code.

Is there a way in this version of preselecting a value when setting up a form from server data on an initial page load?

Keep up the good work guys!

Regards,
Steven.

If you put the following code into the Page_Load for the CascadingDropDown.aspx, it will initialized the first item:

CascadingDropDown1.TargetProperties[0].ClientState ="BMW (value)";

Unfortunately you can't do this for other ones because the change of the first item to the specified value will clear the subsequent items, so we'll need to make improvements here.

But in general the idea is that you should be able to set the ClientState to be the string version of thevalue you want to set (not the text label).

Thinking more about this I think there's a few things we'll do in a future release (might not make our next refresh):

1) Add a strongly typed property for this e.g. "Selected" value

2) Try to make it so the value doesn't flash before the text gets set

3) Make sure you can do more than just the top level here.

Thanks for pointing this out, it's good feedback.

Thanks,

Shawn


So, am I to understand that currently values cannot be selected in dependent lists based on data that that was retrieved from a database?

When I user selects an item to edit, I populate the form with all the existing data for that item, however, some of my dependent lists are not getting the SelectedValue set.

I have an Account list (the parent), I am able to set its SelectedValue.

Sub-Account, Contact, Network and Gateway are dependent on Account. Gateway Version is dependent on Gateway.

When I populate my form the SelectedValue is set successfully for the following lists:

Account, Gateway, Gateway Version

The other lists are disabled and show the PromptText. This would be less confusing to me if ALL dependent lists were disabled with the prompt text selected.

Is there a way to make this work? Or do I need to abandon the CascadingDropDown and find another solution?

(My original post:http://forums.asp.net/thread/1383830.aspx)


It sounds like you have a 1:many parent:child relationship going on here. If so, then I think I fixed the problem withwork item 1704. Please trya recent development release and let us know if it's still not working.

(My app is a ticketing system)

I downloaded the Wed, 30 Aug 2006 17:53:43 GMT version and it solved my issue with the values of the "child" lists not getting selected when viewing/editing an existing ticket. However, now when I go to add a new ticket, my page hangs when it loads the CascadingDropDowns. My cursor becomes an hour glass and my browser becomes unresponsive. My lists never get populated, not even the "parent".

Eventually I get this error: "A script on this page is causing Internet Explorer to run slowly. If it continues to run, your computer may become unresponsive. Do you want to abort the script?"

I'll download a different development release while I wait for a response and see if that makes a difference.

(Side note: I was going to upload a screen shot of the error, but I don't have permission to perform uploads.)


It sounds like either you have a circular reference in your page - or CascadingDropDown is adding one. :) If nothing stands out for you, please post a simple sample so we can have a look. Thanks!

If I add the CascadingDropDownProperties like this (below) the "Add New Ticket" pages hangs on load. However, the "Edit Existing Ticket" page will load/populate just fine - including all of the "child" lists.

<atlasToolkit:CascadingDropDownID="CascadingDropDown1"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="AccountList"

Category="Account"

PromptText="-- Select Account --"

ServiceMethod="GetAccountList"

ServicePath="CascadingListService.asmx"/>

<atlasToolkit:CascadingDropDownProperties

TargetControlID="ExchangeList"

PromptText="-- Select Exchange --"

Category="Exchange"

ServiceMethod="GetExchangeList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

<atlasToolkit:CascadingDropDownID="CascadingDropDown2"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="ContactList"

ParentControlID="AccountList"

PromptText="-- Select Contact --"

Category="Contact"

ServiceMethod="GetContactList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

<atlasToolkit:CascadingDropDownID="CascadingDropDown3"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="SubAccountList"

ParentControlID="AccountList"

PromptText="-- Select Sub-Account --"

Category="SubAccount"

ServiceMethod="GetSubAccountList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

<atlasToolkit:CascadingDropDownID="CascadingDropDown4"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="NetworkList"

ParentControlID="AccountList"

PromptText="-- Select Network --"

Category="Network"

ServiceMethod="GetNetworkList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

<atlasToolkit:CascadingDropDownID="CascadingDropDown5"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="GatewayList"

ParentControlID="AccountList"

PromptText="-- Select Gateway --"

Category="Gateway"

ServiceMethod="GetGatewayList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

<atlasToolkit:CascadingDropDownID="CascadingDropDown6"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="GatewayVersionList"

ParentControlID="GatewayList"

PromptText="-- Select Gateway Version --"

Category="GatewayVersion"

ServiceMethod="GetGatewayVersionList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

____________________________________________________________________________________________________

If I add the CascadingDropDownProperties like this (below) the "Add New Ticket" page loads just fine, however, the "Edit Existing Ticket" page doesn't populate the "child" lists properly - only Account, Gateway, and GatewayVersion have the correct values selected.

<atlasToolkit:CascadingDropDownID="CascadingDropDown1"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="AccountList"

Category="Account"

PromptText="-- Select Account --"

ServiceMethod="GetAccountList"

ServicePath="CascadingListService.asmx"/>

<atlasToolkit:CascadingDropDownProperties

TargetControlID="ExchangeList"

PromptText="-- Select Exchange --"

Category="Exchange"

ServiceMethod="GetExchangeList"

ServicePath="CascadingListService.asmx"/>

<atlasToolkit:CascadingDropDownProperties

TargetControlID="ContactList"

ParentControlID="AccountList"

PromptText="-- Select Contact --"

Category="Contact"

ServiceMethod="GetContactList"

ServicePath="CascadingListService.asmx"/>

<atlasToolkit:CascadingDropDownProperties

TargetControlID="SubAccountList"

ParentControlID="AccountList"

PromptText="-- Select Sub-Account --"

Category="SubAccount"

ServiceMethod="GetSubAccountList"

ServicePath="CascadingListService.asmx"/>

<atlasToolkit:CascadingDropDownProperties

TargetControlID="NetworkList"

ParentControlID="AccountList"

PromptText="-- Select Network --"

Category="Network"

ServiceMethod="GetNetworkList"

ServicePath="CascadingListService.asmx"/>

<atlasToolkit:CascadingDropDownProperties

TargetControlID="GatewayList"

ParentControlID="AccountList"

PromptText="-- Select Gateway --"

Category="Gateway"

ServiceMethod="GetGatewayList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>

<atlasToolkit:CascadingDropDownID="CascadingDropDown3"runat="server">

<atlasToolkit:CascadingDropDownProperties

TargetControlID="GatewayVersionList"

ParentControlID="GatewayList"

PromptText="-- Select Gateway Version --"

Category="GatewayVersion"

ServiceMethod="GetGatewayVersionList"

ServicePath="CascadingListService.asmx"/>

</atlasToolkit:CascadingDropDown>


We'll probably need the corresponding web service (or one that returns close enough data to reproduce the problem), too, please. If this can be reproduced with the SampleWebSite's web service, a demonstration using that is also fine.

Preselecting item in CascadingDropDown from the values in the database

I have a control that you select the state, city, zip. This is then stored in the database. When I want to edit that record, I want it to select the item from the value in the database. How can I accomplish this.

Example:

ID STATE CITY ZIP
0 PA PERKASIE 18944

Gets inserted into database. When editing ID 0, it needs to preselect PA, PERKASIE, 18944 in the cascading drop downs.

Hi,

You can specify a default item in the method that fills the DDL.

And the problem is how to determine which item should be the default one. I think you can keep the information of it in session, when the user clicks a button to start editing. For example:

void btnEdit_Click()

{

CascadingDropDown2.ContextKey = "the value of the item to be preselected";

}

public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(
string knownCategoryValues, string category, string contextKey)
{
AjaxControlToolkit.CascadingDropDownNameValue[] result = new AjaxControlToolkit.CascadingDropDownNameValue[10];
for (int i = 0; i < 10; i++)
{
result[i] = new AjaxControlToolkit.CascadingDropDownNameValue();
result[i].name = i.ToString() + " " + category + " of " + knownCategoryValues + "name";
result[i].value = i.ToString() + " " + category + " of " + knownCategoryValues + "value";

if(result[i] == contextKey) result[i].isDefaultValue = true;
}
return result;
}


Hope this helps.


Putting this somewhere in the page initialization might work, too:

MyCascadingStateDropDown1.SelectedValue = mystateid;

This seems to invoke the WebMethod to prepopulate the list, preselect the default, and invoke the cascade.



Yes, this help!


I am using the CascadingDropDownList control for two DropDownList I have on my page. The first is a GroupType and the seccond is a Group. I hvae this all working with loading the data from the WebService. All works great except for when I try to go into the Edit Mode. In Edit Mode, I need to set the two DropDwonList with the items the user selected in edit mode.

Here is a section of my code from the C# side of things where I am trying to set the ContextKey...

CascadingDropDownGroupType.ContextKey = dr2["GRPLKUPiGroupType"].ToString();

CascadingDropDownGroup.ContextKey = dr2["GRPLKUPsGroupCode"].ToString();

Here is my WebService Code... (I have included the complete WebService) Keep in mind the WebService works fine, I just need to know where / how to set the items I want to display as SELECTED in the DDL when the user goes into EDIT MODE.

using System;

using System.Web;

using System.Collections;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.SessionState;

using AjaxControlToolkit;

using System.Data;

using System.Data.SqlClient;

using System.Web.Script.Services;

using boyce;

///<summary>

///</summary>

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

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

publicclassBoyceWebService : System.Web.Services.WebService

{

public BoyceWebService()

{

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod(true)]publicCascadingDropDownNameValue[] GetTheGroupTypes(string knownCategoryValues,string category)

{

string[] sArray =newstring[10];

SessionManager CurrentSession;

CurrentSession =SessionManager.GetSessionInfo();

if (CurrentSession !=null)

{

category = CurrentSession.iSelectedGroupTypeId.ToString();

}

else

{

System.Diagnostics.Debug.WriteLine("GetTheGroupTypes -- Session NULL");

}

string DSN = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolFinancialConnectionString1"].ToString();

DataSet ds =newDataSet();

object oSTRUCT =newobject();

string sSQL =string.Empty;

DataCallManager.InitArray();

sArray[0] =string.Empty;

sArray[1] ="-1";

sArray[2] =string.Empty;

sSQL =DataCall.GetSQL("tblLookupGroupTypes_T","S9", sArray, oSTRUCT);SqlConnection cn =newSqlConnection(DSN);

cn.Open();

SqlDataAdapter dscmd =newSqlDataAdapter(sSQL, cn);

dscmd.Fill(ds,"DCM_Get");

List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();

if (ds.Tables.Count != 0)

{

foreach (DataRow drLOOPin ds.Tables[0].Rows)

{

string sTheGroupType = (string)drLOOP["GRPTYPsGroupType"];

int iTheGroupTypeId = (int)drLOOP["GRPTYPiID"];

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString()));

}

}

cn.Close();

dscmd.Dispose();

cn.Dispose();

return values.ToArray();

}

[WebMethod(true)]publicCascadingDropDownNameValue[] GetTheGroupsForTheGroupType(string knownCategoryValues,string category)

{

StringDictionary kv =CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int iTheGroupTypeId = -1;if (!kv.ContainsKey("GroupType") || !Int32.TryParse(kv["GroupType"],out iTheGroupTypeId))

{

returnnull;

}

string[] sArray =newstring[10];

string DSN = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolFinancialConnectionString1"].ToString();

DataSet ds =newDataSet();

object oSTRUCT =newobject();

string sSQL =string.Empty;

DataCallManager.InitArray();

sArray[0] =Convert.ToString(iTheGroupTypeId);

sArray[1] ="-1";

sArray[2] =string.Empty;

sSQL =DataCall.GetSQL("tblLookupGroupTypes_T","S10", sArray, oSTRUCT);SqlConnection cn =newSqlConnection(DSN);

cn.Open();

SqlDataAdapter dscmd =newSqlDataAdapter(sSQL, cn);

dscmd.Fill(ds,"DCM_Get");

List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();

if (ds.Tables.Count != 0)

{

foreach (DataRow drLOOPin ds.Tables[0].Rows)

{

values.Add(newCascadingDropDownNameValue((string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPiID"].ToString()));

}

}

cn.Close();

dscmd.Dispose();

cn.Dispose();

return values.ToArray();

}

}


I figured this one out.. All you have to do is in the WebService add / replace the values add with the following

if (Convert.ToInt32(CurrentSession.iSelectedGroupTypeId.ToString()) == iTheGroupTypeId)

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),true));

}

else

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),false));

}


Does anybody know then why setting the isDefaultValue (the third parameter to the constructor of CascadingDropDownNameValue) doesn't do anything? I have debugged my page to confirm that I am indeed setting that value however when the webmethod returns the results it always selects the first value.

Any help would be greatly appreciated.

Thanks,


I did get this to work, and here is the complete WebService I used. Now keep in mind that some of the code will not apply as it references our data access layer we use. However the part you are asking about is there and working. You basically set the "contextKey" inside your normal code and then the web service has to be modified to pass that "contextKey" in. From there, you use the value of the "contextKey" to know if you should set the DefaultValue or not.

In your code, when the page is loaded, you set the value of the context key to what your DEFAULT VALUES are to be. In my example, I have a DDL for GROUP TYPE and a DDL for GROUP.

CascadingDropDownGroupType.ContextKey = dr2["GRPLKUPiGroupType"].ToString();

CascadingDropDownGroup.ContextKey = dr2["GRPLKUPsGroupCode"].ToString();

==================================================================================

Here is the WebService Code.....

==================================================================================

using System;

using System.Web;

using System.Collections;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.SessionState;

using AjaxControlToolkit;

using System.Data;

using System.Data.SqlClient;

using System.Web.Script.Services;

using boyce;

///<summary>

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

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

publicclassBoyceWebService : System.Web.Services.WebService

{

public BoyceWebService()

{

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod(true)]publicCascadingDropDownNameValue[] GetTheGroupTypes(string knownCategoryValues,string category,string contextKey)

{

string[] sArray =newstring[10];

SessionManager CurrentSession;

CurrentSession =SessionManager.GetSessionInfo();

string DSN = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolFinancialConnectionString1"].ToString();

DataSet ds =newDataSet();

object oSTRUCT =newobject();

string sSQL =string.Empty;

DataCallManager.InitArray();

sArray[0] = CurrentSession.sSelectedGroupScreenTYPE;

sArray[1] = contextKey.ToString();

sSQL =DataCall.GetSQL("tblLookupGroupTypes_T","S9", sArray, oSTRUCT);SqlConnection cn =newSqlConnection(DSN);

cn.Open();

SqlDataAdapter dscmd =newSqlDataAdapter(sSQL, cn);

dscmd.Fill(ds,"DCM_Get");

List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();

if (ds.Tables.Count != 0)

{

foreach (DataRow drLOOPin ds.Tables[0].Rows)

{

string sTheGroupType = (string)drLOOP["GRPTYPsGroupType"];

int iTheGroupTypeId = (int)drLOOP["GRPTYPiID"];

if (contextKey.ToString().Trim() !=string.Empty || contextKey.ToString().Trim() !="-1")

{

if (Convert.ToInt32(contextKey.ToString()) == iTheGroupTypeId)

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),true));

}

else

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),false));

}

}

else

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString()));

}

}

}

cn.Close();

dscmd.Dispose();

cn.Dispose();

return values.ToArray();

}

[WebMethod(true)]publicCascadingDropDownNameValue[] GetTheGroupsForTheGroupType(string knownCategoryValues,string category,string contextKey)

{

StringDictionary kv =CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int iTheGroupTypeId = -1;if (!kv.ContainsKey("GroupType") || !Int32.TryParse(kv["GroupType"],out iTheGroupTypeId))

{

returnnull;

}

string[] sArray =newstring[10];

string DSN = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolFinancialConnectionString1"].ToString();

DataSet ds =newDataSet();

object oSTRUCT =newobject();

string sSQL =string.Empty;

DataCallManager.InitArray();sArray[0] =Convert.ToString(iTheGroupTypeId);

sArray[1] = contextKey.ToString();

sSQL =DataCall.GetSQL("tblLookupGroupTypes_T","S10", sArray, oSTRUCT);

SqlConnection cn =newSqlConnection(DSN);

cn.Open();

SqlDataAdapter dscmd =newSqlDataAdapter(sSQL, cn);

dscmd.Fill(ds,"DCM_Get");

List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();if (ds.Tables.Count != 0)

{

foreach (DataRow drLOOPin ds.Tables[0].Rows)

{

if (contextKey.ToString().Trim() !=string.Empty || contextKey.ToString().Trim() !="-1")

{

if (drLOOP["GRPLKUPsGroupCode"].ToString() == contextKey.ToString())

{

values.Add(newCascadingDropDownNameValue(

(string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPsGroupCode"].ToString(),true));

}

else

{

values.Add(newCascadingDropDownNameValue((string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPsGroupCode"].ToString(),false));

}

}

else

{

values.Add(newCascadingDropDownNameValue((string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPsGroupCode"].ToString()));

}

}

}

cn.Close();

dscmd.Dispose();

cn.Dispose();

return values.ToArray();

}

}


I have no idea what happened to my last post.. SORRY.. Here is the WebService code...

using System;

using System.Web;

using System.Collections;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.SessionState;

using AjaxControlToolkit;

using System.Data;

using System.Data.SqlClient;

using System.Web.Script.Services;

using boyce;

///<summary>

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

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

publicclassBoyceWebService : System.Web.Services.WebService

{

public BoyceWebService()

{

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod(true)]publicCascadingDropDownNameValue[] GetTheGroupTypes(string knownCategoryValues,string category,string contextKey)

{

string[] sArray =newstring[10];

SessionManager CurrentSession;

CurrentSession =SessionManager.GetSessionInfo();

string DSN = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolFinancialConnectionString1"].ToString();

DataSet ds =newDataSet();

object oSTRUCT =newobject();

string sSQL =string.Empty;

DataCallManager.InitArray();

sArray[0] = CurrentSession.sSelectedGroupScreenTYPE;

sArray[1] = contextKey.ToString();

sSQL =DataCall.GetSQL("tblLookupGroupTypes_T","S9", sArray, oSTRUCT);SqlConnection cn =newSqlConnection(DSN);

cn.Open();

SqlDataAdapter dscmd =newSqlDataAdapter(sSQL, cn);

dscmd.Fill(ds,"DCM_Get");

List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();

if (ds.Tables.Count != 0)

{

foreach (DataRow drLOOPin ds.Tables[0].Rows)

{

string sTheGroupType = (string)drLOOP["GRPTYPsGroupType"];

int iTheGroupTypeId = (int)drLOOP["GRPTYPiID"];

if (contextKey.ToString().Trim() !=string.Empty || contextKey.ToString().Trim() !="-1")

{

if (Convert.ToInt32(contextKey.ToString()) == iTheGroupTypeId)

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),true));

}

else

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),false));

}

}

else

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString()));

}

}

}

cn.Close();

dscmd.Dispose();

cn.Dispose();

return values.ToArray();

}

[WebMethod(true)]publicCascadingDropDownNameValue[] GetTheGroupsForTheGroupType(string knownCategoryValues,string category,string contextKey)

{

StringDictionary kv =CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int iTheGroupTypeId = -1;if (!kv.ContainsKey("GroupType") || !Int32.TryParse(kv["GroupType"],out iTheGroupTypeId))

{

returnnull;

}

string[] sArray =newstring[10];

string DSN = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolFinancialConnectionString1"].ToString();

DataSet ds =newDataSet();

object oSTRUCT =newobject();

string sSQL =string.Empty;

DataCallManager.InitArray();sArray[0] =Convert.ToString(iTheGroupTypeId);

sArray[1] = contextKey.ToString();

sSQL =DataCall.GetSQL("tblLookupGroupTypes_T","S10", sArray, oSTRUCT);

SqlConnection cn =newSqlConnection(DSN);

cn.Open();

SqlDataAdapter dscmd =newSqlDataAdapter(sSQL, cn);

dscmd.Fill(ds,"DCM_Get");

List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();if (ds.Tables.Count != 0)

{

foreach (DataRow drLOOPin ds.Tables[0].Rows)

{

if (contextKey.ToString().Trim() !=string.Empty || contextKey.ToString().Trim() !="-1")

{

if (drLOOP["GRPLKUPsGroupCode"].ToString() == contextKey.ToString())

{

values.Add(newCascadingDropDownNameValue(

(string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPsGroupCode"].ToString(),true));

}

else

{

values.Add(newCascadingDropDownNameValue((string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPsGroupCode"].ToString(),false));

}

}

else

{

values.Add(newCascadingDropDownNameValue((string)drLOOP["GRPLKUPsGroupName"], drLOOP["GRPLKUPsGroupCode"].ToString()));

}

}

}

cn.Close();

dscmd.Dispose();

cn.Dispose();

return values.ToArray();

}

}


Hmmm. I am not using a context key but I am still conditionally adding the true parameter to the new cascadingdropdownvalue. Also, from my understanding of its constructor, isDefaultValue defaults to false if a bool is not passed. Below is my code, I am using the selected value from the previous dropdownlist to try and set the selected value of this drop down list. (And yes, the previous dropdownlist has the same elements in it as this one does).

Thanks for responding.

[WebMethod]public static CascadingDropDownNameValue[] GetTestKeys(string knownCategoryValues,string category) {StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);if (!kv.ContainsKey("officeType") || String.IsNullOrEmpty(kv["officeType"])) {return null;}OracleCommand cmdGetTestKeys =new OracleCommand(@."SELECT test_key, test_key || ' ' || test_orgn || ' ' || test_subj as description FROM linc.pccdb_ttestWHERE test_user = :p_OfficeORDER BY test_key",new OracleConnection(ConfigurationManager.ConnectionStrings["PCCDB_Web"].ConnectionString));cmdGetTestKeys.Parameters.AddWithValue("p_Office", kv["officeType"]);cmdGetTestKeys.Connection.Open();OracleDataReader drTestKeys = cmdGetTestKeys.ExecuteReader();List values =new List();Object[] keyValuePair =new Object[2];string value = String.Empty;while (drTestKeys.Read() ==true) {drTestKeys.GetValues(keyValuePair);value = Convert.ToInt32(keyValuePair[0]).ToString();//Check for the headerTestKey, if it exits then popluate the set for the header,//otherwise setup the detail test key to match the headerTestKey.if (!kv.ContainsKey("headerTestKey") || String.IsNullOrEmpty(kv["headerTestKey"])) {values.Add(new CascadingDropDownNameValue((string)keyValuePair[1],value));}else {if (value == kv["headerTestKey"]) {values.Add(new CascadingDropDownNameValue((string)keyValuePair[1],value,true));}else {values.Add(new CascadingDropDownNameValue((string)keyValuePair[1],value));}}}cmdGetTestKeys.Connection.Close();return values.ToArray();}

From the initial look at your code, I would agree, it should work fine.

One thing I ran into, and fought for days because I was "SURE" I had it correct, was the key names. You may want to consider placing some debug statements around the "IF/ELSE" logic to see exactly what part of the code is being hit. I placed some breakpoints in my code and examined the key collection. I found I was looking for the incorrect key name and thus never hitting the code I was thinking it was hitting. I know that sounds basic, but from looking at your code it should work, due to the fact it is not working, I am guessing it may not be hitting the code you expect.

I would examine the flow around this section and make 100% sure the key you are looking for "headerTestKey" really exists in the key collection.

If this does not work, post you entire webserice and I will take a look at it and try to recreate the problem on my side.

Good Luck...

if (!kv.ContainsKey("headerTestKey") || String.IsNullOrEmpty(kv["headerTestKey"])) {
values.Add(new CascadingDropDownNameValue((string)keyValuePair[1],value));
}
else {
if (value == kv["headerTestKey"]) {
values.Add(new CascadingDropDownNameValue((string)keyValuePair[1],value,true));
}
else {
values.Add(new CascadingDropDownNameValue((string)keyValuePair[1],value));
}
}


this almost works for me. Almost...

I have a gridview on my page and when i click on edit command of gridview row, three dropdowns have to be populated with default value based on row data.

So gridview_rowediting is called firstly. I declare contextkeys for all of my dropdowns here.

Next, WebMethods do their job. I found out they do it properly while debbuging.

But the problem is that only first time calling "edit" this works. Then there are always same items choosen. Seems strange because webmethods do their job.

What could be wrong?


Some things you may try... (You may have already tried these items)

1. Make sure each time your gridview_rowediting fires, that the context keys are being set with the values you are expecting. I knwo, from working with GridViews in the past, that you have to be careful to get the correct row values.

CascadingDropDownGroupType.ContextKey = dr2["GRPLKUPiGroupType"].ToString();

CascadingDropDownGroup.ContextKey = dr2["GRPLKUPsGroupCode"].ToString();

2. Once you have verified the ContextKeys are being set properly, make sure the are correctly set inside the WebMethod. Just to make sure nothing got hosed up in the passing of the ContextKeys.

Just display / examine thecontextKey.ToString().Trim() to make sure each of them are properly set based on the data from the row edit.

3. Make sure you aer setting the DEFAULT VALUE is TRUE for the matching ContextKey Value.

if (Convert.ToInt32(contextKey.ToString()) == iTheGroupTypeId)

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),true));

}

else

{

values.Add(newCascadingDropDownNameValue(sTheGroupType, iTheGroupTypeId.ToString(),false));

}

4. Make sure the values passed from one WebMethod to the other is set / used correctly. For example, I have 2 CDDL in my code. One is Group Type and the other is Group. In the 2nd WebMethod I use the following to get the value passed from the 1st WebMethod. Verify you have this set in your code from WebMethod to WebMethod and make sure the highlighted items "out" is being set correctly.

StringDictionary kv =CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int iTheGroupTypeId = -1;

if (!kv.ContainsKey("GroupType") || !Int32.TryParse(kv["GroupType"],out iTheGroupTypeId))

{

returnnull;

}

I hope this helps.. If not, post your complete WebService code and I will do what I can to try and look at it and help you out.

Best of Luck... Cool


As I said, i debbuged the web service and checked all these things. There are no problems with contexKey - it allways holds the value needed. So the code

For Each row As DataRow In gds.Tables(0).Rows
If cint(row("id_project")) = cint(contextKey) Then
values.Add(New CascadingDropDownNameValue( _
row("name"), row("id_project"), True))
Else
values.Add(New CascadingDropDownNameValue( _
row("name"), row("id_project"), False))
End If
Next

always "finds" the item needed. It's just not displayed then...


it works now. I had to put

dropdownlist.SelectedValue = -1

for all my dropdowns in datagrid_RowEditing sub

Saturday, March 24, 2012

Problem creating binding for TextBox/AutoCompleteExtender and DropDownList/CascadingDropDo

I'm trying to use a textbox hooked up to an autocompleteextender todrive a DropDownList hooked up to a cascadingdropdown. I'm tryingto do this by creating a binding between the textbox and a hiddenDropDownList. The binding invokes a custom transform that updatesthe contents on the hidden dropdown with the text from the textbox whenthe textbox text changes. I am close, but I am running into someissues which I believe are due to the fact that my controls are insidean updatepanel. I'm getting the infamous Duplicate use of id...when the updatepanel reloads my textbox and autocompleteextender.

Here's the source. Can anyone offer any ideas? thanks...

<%@dotnet.itags.org. Page Language="C#" EnableEventValidation="false" %>
<%@dotnet.itags.org. Register Assembly="AtlasControlToolkit" Namespace="AtlasControlToolkit" TagPrefix="atlasToolkit" %
<script runat="server">

void AutoCompleteTextBox_PreRender(object sender, EventArgs e) {
((TextBox)sender).Attributes.Add("autocomplete", "off");
}

void Page_Load(object sender, EventArgs e) {

AccountTextBox.Visible = AccountRadioButton.Checked;
if (AccountRadioButton.Checked) {AccountAutoCompleteExtender.TargetProperties[0].Enabled = true; }
else {
AccountAutoCompleteExtender.TargetProperties.Clear();
CascadingDropDown1.TargetProperties.Clear();
}

LicenseTextBox.Visible = LicenseRadioButton.Checked;
LicenseDropDownList.Visible = !LicenseRadioButton.Checked;
if (LicenseRadioButton.Checked) {LicenseAutoCompleteExtender.TargetProperties[0].Enabled = true; }
else { LicenseAutoCompleteExtender.TargetProperties.Clear(); }

}

</script
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
<!-- //

var addl;
var atb;

function pageLoad(sender, e) {

atb = new Sys.UI.TextBox($("<%=AccountTextBox.ClientID %>"));
addl = new Sys.UI.Select($("<%=AccountDropDownList.ClientID %>"));

var addl_binding = new Sys.Binding();
addl_binding.set_dataContext(atb);
addl_binding.set_dataPath("text");
addl_binding.set_property("selectedValue");
addl_binding.transform.add(setDropDownList);

addl.get_bindings().add(addl_binding);

atb.initialize();
addl.initialize();
}

function setDropDownList(sender, eventArgs) {

// I WOULD HAVE LIKED TO HAVE CREATED AN INSTANCE OFTHE AtlasControlToolkit.CascadingDropDownNameValue,
// BUT COULDN'T SEEM TO FIGURE OUT HOW TO DO THAT...
var value = newDummy.CascadingDropDownNameValue(eventArgs.get_value(),eventArgs.get_value());

var cddp1 = $object("CascadingDropDownProperties1");
cddp1._setOptions([value]);

}

// -->
</script>

</head>
<body>
<form id="form1" runat="server">
<atlas:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

<atlas:AutoCompleteExtender ID="AccountAutoCompleteExtender" runat="server">
<atlas:AutoCompleteProperties Enabled="true" MinimumPrefixLength="2"ServiceMethod="GetAccountList" ServicePath="Lookup.asmx"TargetControlID="AccountTextBox" />
</atlas:AutoCompleteExtender
<atlas:AutoCompleteExtender ID="LicenseAutoCompleteExtender" runat="server">
<atlas:AutoCompleteProperties Enabled="true" MinimumPrefixLength="2"ServiceMethod="GetLicenseList" ServicePath="Lookup.asmx"TargetControlID="LicenseTextBox" />
</atlas:AutoCompleteExtender>

<atlasToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server">
<atlasToolkit:CascadingDropDownPropertiesid="CascadingDropDownProperties1" TargetControlID="AccountDropDownList"Category="Account" PromptText="" ServicePath="~/FrontlineService.asmx"ServiceMethod="GetDropDownTextBoxContents" />
<atlasToolkit:CascadingDropDownPropertiesTargetControlID="LicenseDropDownList" Category="License"PromptText="Please select a License"ServicePath="~/FrontlineService.asmx"ServiceMethod="GetDropDownTextBoxContents"ParentControlID="AccountDropDownList" />
</atlasToolkit:CascadingDropDown>

<asp:Panel ID="LookupPanel" BackColor="#999999" CssClass="panel" runat="server">
<atlas:UpdatePanel ID="LookupUpdatePanel" Mode="Conditional"runat="server">
<ContentTemplate>
<div>
<table>
<tr>
<td rowspan="3"valign="top"><span style="font-weight: bold;">License LookupBy:</span></td>
<td>
<asp:RadioButtonID="AccountRadioButton" GroupName="Lookup" Checked="true"AutoPostBack="true" runat="server" /> Account
</td>
<td>
<asp:TextBoxID="AccountTextBox" OnPreRender="AutoCompleteTextBox_PreRender"runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButtonID="LicenseRadioButton" GroupName="Lookup" AutoPostBack="true"runat="server" /> License
</td>
<td>
<asp:TextBoxID="LicenseTextBox" OnPreRender="AutoCompleteTextBox_PreRender"runat="server" />
<asp:DropDownListID="AccountDropDownList" style="display: none;" runat="server"/>
<asp:DropDownListID="LicenseDropDownList" runat="server" />
</td>
</tr>
</table>
</div>

<scripttype="text/xml-script">
<pagexmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
</components>
</page>
</script>

</ContentTemplate>
<Triggers>
<atlas:ControlEventTriggerControlID="AccountRadioButton" EventName="CheckedChanged" />
<atlas:ControlEventTriggerControlID="LicenseRadioButton" EventName="CheckedChanged"/>
</Triggers>
</atlas:UpdatePanel>

</asp:Panel>

</form
<script type="text/javascript">
<!-- //

Type.registerNamespace("Dummy");

Dummy.CascadingDropDownNameValue = function(name, value) {
var _name = name;
var _value = value;

this.name = _name;
this.value = _value;

}

Dummy.CascadingDropDownNameValue.registerClass('Dummy.CascadingDropDownNameValue');
// -->
</script
</body>
</htmlHave you tried FAQ #6?
I did read that, and I did try to apply the
var context = Sys.Application.getMarkupContext();
if (context) { context.removeObject(this); }

to the dispose method of the CascadingDropDownBehavior.js but it didn't seem to make a difference.

I'm stilling getting the Duplicate use for the AccountTextBox, CascadingDropDownProperties1 and AccountDropDownList...
I'm trying a slightly different approach, but I'm still running intosome issues. I'm trying to define the autocomplete behaviordeclaratively, instead of using an autocompleteextender. everything works well, but when the updatepanel refreshes, theautocomplete behavior doesn't seem to exist anymore.

i tried placing the xml-script inside the updatepanel, too, no difference.

heres the code to reproduce:

<%@. Page Language="C#" EnableEventValidation="false" %
<%@. Register Assembly="AtlasControlToolkit" Namespace="AtlasControlToolkit" TagPrefix="atlasToolkit" %
<script runat="server">

void AutoCompleteTextBox_PreRender(object sender, EventArgs e) {
((TextBox)sender).Attributes.Add("autocomplete", "off");
}

</script
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title
<script type="text/javascript">
<!-- //

function setDropDownList(sender, eventArgs) {

// I WOULD HAVE LIKED TOHAVE CREATED AN INSTANCE OF THEAtlasControlToolkit.CascadingDropDownNameValue,
// BUT COULDN'T SEEM TO FIGURE OUT HOW TO DO THAT...
var value = newDummy.CascadingDropDownNameValue(sender.get_text(), sender.get_text());

var cddp1 = $object("CascadingDropDownProperties1");
cddp1._setOptions([value]);

}

// -->
</script
</head>
<body>
<form id="form1" runat="server">
<atlas:ScriptManagerid="ScriptManager1" EnablePartialRendering="true" runat="server" />

<atlas:AutoCompleteExtender id="LicenseAutoCompleteExtender" runat="server">
<atlas:AutoCompleteProperties Enabled="true" MinimumPrefixLength="2"ServiceMethod="GetLicenseList" ServicePath="Lookup.asmx"TargetControlID="LicenseTextBox" />
</atlas:AutoCompleteExtender>

<atlasToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server">
<atlasToolkit:CascadingDropDownPropertiesID="CascadingDropDownProperties1" TargetControlID="AccountDropDownList"Category="Account" PromptText="" ServicePath="~/FrontlineService.asmx"ServiceMethod="GetDropDownContents" />
<atlasToolkit:CascadingDropDownPropertiesTargetControlID="LicenseDropDownList" Category="License"PromptText="Please select a License"ServicePath="~/FrontlineService.asmx"ServiceMethod="GetDropDownContents" ParentControlID="AccountDropDownList" />
</atlasToolkit:CascadingDropDown
<script type="text/xml-script">
<pagexmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<textBox id="AccountTextBox"propertyChanged="setDropDownList">
<behaviors>
<autoComplete completionInterval="1000"completionList="completionList" completionSetCount="15"
dataContext="AccountTextBox" minimumPrefixLength="2"serviceMethod="GetAccountList"
serviceURL="Lookup.asmx">
</autoComplete>
</behaviors>
</textBox>
</components>
</page>
</script
<asp:Panel ID="LookupPanel" BackColor="#999999" CssClass="panel" runat="server">
<atlas:UpdatePanel id="LookupUpdatePanel" mode="Conditional"runat="server">
<ContentTemplate>
<div>
<table>
<tr>
<td rowspan="3" valign="top"><spanstyle="font-weight: bold;">License Lookup By:</span></td>
<td>
<asp:RadioButton ID="AccountRadioButton"GroupName="Lookup" Checked="true" AutoPostBack="true" runat="server"/> Account
</td>
<td>
<asp:TextBox ID="AccountTextBox"OnPreRender="AutoCompleteTextBox_PreRender" runat="server" />
<div id="completionList"></div>
<asp:DropDownList ID="AccountDropDownList"style="display: none;" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="LicenseRadioButton"GroupName="Lookup" AutoPostBack="true" runat="server" /> License
</td>
<td>
<asp:TextBox ID="LicenseTextBox"OnPreRender="AutoCompleteTextBox_PreRender" runat="server" />
<asp:DropDownList ID="LicenseDropDownList"runat="server" />
</td>
</tr>
</table>
</div>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTriggerControlID="AccountRadioButton" EventName="CheckedChanged" />
<atlas:ControlEventTriggerControlID="LicenseRadioButton" EventName="CheckedChanged" />
</Triggers>
</atlas:UpdatePanel>
</asp:Panel>
</form
<script type="text/javascript">
<!-- //

Type.registerNamespace("Dummy");

Dummy.CascadingDropDownNameValue = function(name, value) {
var _name = name;
var _value = value;

this.name = _name;
this.value = _value;
}

Dummy.CascadingDropDownNameValue.registerClass('Dummy.CascadingDropDownNameValue');
// -->
</script
</body>
</html

Problem getting SelectedValue of Cascading DropDown inside a Gridview

I am trying to obtain the SelectedValue from a DropDownList which is controlled by a CascadingDropDown Control both of which are inside of a gridview. The cascading dropdowns are populating correctly. The SelectedValue is also set on these dropdowns in the OnRowDataBound event.

In the OnRowUpdating event, I am grabbing the dropdownlist's selected value from the updating row using:

string strID = ((

DropDownList)gvPositions.Rows[e.RowIndex].FindControl("ddlLineEdit")).SelectedValue;

When I do this, the value is always null.

I think it might be because you don't reference the cell but only the row. I have a similar example that does work:

DropDownList ddPanes = (DropDownList)grid.Rows[e.RowIndex].Cells[2].FindControl("ddPaneNames");

Hope it helps,

Joe
That was a good thought. I don't have to do that for the other controls in the row, but I tried it. Unfortunately that still give me null as well.
Can you post the markup for your gridview?

Here is my code:

<asp:GridView ID="gvPositions" runat="server" AutoGenerateColumns="False" Width="100%" OnRowEditing="gvEdit" OnRowCancelingEdit="gvCancel" OnRowUpdating="gvUpdate" OnRowCommand="gvItemCommand" OnRowDeleting="gvDelete" OnRowDataBound="gvRowDataBind"> <Columns> <asp:TemplateField HeaderText="positionID" Visible="False"> <ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.positionID")%>' ID="lblpositionID"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.positionID")%>' ID="lblpositionID"> </asp:Label> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="TDA Version"> <ItemTemplate> <asp:Label runat="server" Text='<%# Eval("tdaName")%>' ID="lbltdaNameGrid"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="lbltdaNameEdit" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.tdaName")%>'> </asp:Label> <asp:DropDownList ID="ddlTDANameEdit" runat="server" AutoPostBack="false" DataSource='<%# GetTDAList()%>' SelectedValue='<%# Eval("tdaVersionID")%>' DataTextField="tdaName" DataValueField="tdaVersionID" ></asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Paragraph"> <ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.paragraphTitle")%>' ID="lblParagraphNameGrid"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="lblParagraphEdit" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.paragraphTitle")%>'> </asp:Label> <asp:DropDownList ID="ddlParagraphEdit" runat="server" AutoPostBack="false"></asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Line"> <ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.lineTitle")%>' ID="lbltitleGrid"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label runat="server" ID="lbltitleEdit" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.lineTitle")%>'> </asp:Label> <asp:DropDownList ID="ddlLineEdit" runat="server" AutoPostBack="false"></asp:DropDownList> <cc1:CascadingDropDown ID="CascadingDropDownGridView" runat="server" SuppressValidationScript="true"> <cc1:CascadingDropDownProperties TargetControlID="ddlParagraphEdit" ServiceMethod="GetParagraphsByTDAID" ServicePath="~/AutoCompleteService.asmx" PromptText="Please select a paragraph" Category="tdaVersionID" ParentControlID="ddlTDANameEdit" /> <cc1:CascadingDropDownProperties TargetControlID="ddlLineEdit" ServiceMethod="GetLinesByParagraphID" ServicePath="~/AutoCompleteService.asmx" PromptText="Please select a line" Category="tdaParagraphID" ParentControlID="ddlParagraphEdit" /> </cc1:CascadingDropDown> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Directorate"> <ItemTemplate> <asp:Label runat="server" ID="lblDirectorate" Text='<%# DataBinder.Eval(Container, "DataItem.directorateSymbol")%>' width="100%"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList runat="server" id="ddlDirectorate" CssClass="label" Width="100%" DataSource='<%# GetDirectorateList()%>' SelectedIndex='<%# GetSelectedDirectorate(DataBinder.Eval(Container, "DataItem.directorateID").ToString())%>' DataTextField="directorateSymbol" DataValueField="directorateID"> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Division" ControlStyle-Width="100px"> <ItemTemplate> <asp:Label runat="server" ID="lblDivision" Text='<%# DataBinder.Eval(Container, "DataItem.officeSymbol")%>' width="100%"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList runat="server" id="ddlDivision" CssClass="label" Width="100%" DataSource='<%# GetDivisionList()%>' SelectedIndex='<%# GetSelectedDivision(DataBinder.Eval(Container, "DataItem.divisionID").ToString())%>' DataTextField="officeSymbol" DataValueField="divisionID"> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Start Date
<ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.dateStartText")%>' ID="lblGridDateStart"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtGridDateStart" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.dateStartText")%>'> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="End Date
<ItemTemplate> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.dateEndText")%>' ID="lblGridDateEnd"> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtGridDateEnd" CssClass="label" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.dateEndText")%>'> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Current Position"> <ItemTemplate> <asp:CheckBox ID="chkbxPositionCurrentDisplay" runat="server" Checked='<%# DataBinder.Eval(Container, "DataItem.positionCurrent")%>' Enabled="false" /> </ItemTemplate> <EditItemTemplate> <asp:CheckBox ID="chkbxPositionCurrent" runat="server" Checked='<%# DataBinder.Eval(Container, "DataItem.positionCurrent")%>' /> </EditItemTemplate> </asp:TemplateField> <asp:CommandField ShowEditButton="True" CancelImageUrl="~/images/cancel.gif" ShowDeleteButton="True" DeleteImageUrl="~/images/delete.gif" EditImageUrl="~/images/edit.gif" UpdateImageUrl="~/images/save.gif" ButtonType="Image" /> </Columns> </asp:GridView>

The code I listed above us on a Web User Control called by another Web User Control which is called by a Web Form. I recreated the Gridview on a new page this morning with all the code behind and it worked.

So I am wondering if this has to do with when the Page_Load get called for each control. I would really like to get it to work on the control.


Could this be a symptom the cause of work item 640?

Problem getting SelectedIndex from CascadingDropDown in an UpdatePanel

Hey everyone, I'm having an issue with my AJAX page. I have a CascadingDropDown that once a value is selected, trigger the population of another CascadingDropDown that resides in an UpdatePanel. I'm attempting to have the second CascadingDropDown populate a textbox based on its .SelectedIndex. For some reason, I can grab the .SelectedValue, but getting .SelectedIndex always returns 0.

Does anyone else have this problem, or know how to solve it. Any help would be greatly appreciated.

Did you find a solution for your problem? Coz I also have the same problem

hi,

please refer :http://ajax.asp.net/ajaxtoolkit/CascadingDropDown/CascadingDropDown.aspx

please post the code, so that i can help you to solve your problem.

Thanks

Kishore.

www.relgo.com


hello invisible man,

thanks for the reply, here is my scenario... i have two cascadingdropdown control on my page, and then I have a dynamicpopulate control (which is binded or the targetcontrol is a textbox) that is dependent on the selected value of the two cascadingdropdown control. The problem is passing the value of both the cascadeddropdown control to the dynamicpopulate control.

here is my aspx code (i did not include the master page)

123<%@.4Page Language="C#"5MasterPageFile="~/NOCMasterPage.master"6AutoEventWireup="true"7CodeFile="ApplicationForm.aspx.cs"8Inherits="ApplicationForm"9Title="Sharjah NOC Application Form"10EnableEventValidation="false" %>1112<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>1314"ApplicationFormContent" ContentPlaceHolderID="cphNOCMasterPage" Runat="Server">15 "smApplicationForm" runat="server">1617 "text/javascript">18 function SelectFromDDL(ddPlotNumberID, ddAreaNameID)19 {20 alert(document.getElementsByName(ddPlotNumberID));21 var e = document.getElementsByName(ddPlotNumberID);// get ddPlotNumber element22 alert(eval([e.selectedIndex].text));2324 }2526 function fnContextValue(strSelectedAreaNameSelectedPlotNo)27 {28 var behaviorId = $find('dpePlotAreaID');29if (behaviorId)30 {31 behaviorId.populate(strSelectedAreaNameSelectedPlotNo);32 }3334 }3536

3738 39 "lblAreaName" runat="server" Text="Area Name" Width="238px" Font-Names="Arial" ForeColor="MidnightBlue">40 "ddAreaName" runat="server" EnableViewState="false">4142 "cddAreaName" runat="server"43 PromptText="Please select the Area in Manhattan"44 LoadingText="Loading ...."45 TargetControlID="ddAreaName"46 ServicePath ="PlotAreaService.asmx"47 ServiceMethod ="GetAreaName"48 Category="AreaName">4950

51

52 53 "lblPlotNumber" runat="server" Text="Plot Number" Width="238px" Font-Names="Arial" ForeColor="MidnightBlue">54 55 "ddPlotNumber" runat="server">565758 "cddPlotNo" runat="server"59 TargetControlID="ddPlotNumber"60 ParentControlID="ddAreaName"61 PromptText="Please select Plot Number inside the selected Area"62 ServicePath ="PlotAreaService.asmx"63 ServiceMethod ="GetPlotNo" Category="PlotNo">6465

66

67 68 "lblPlotArea" runat="server" Text="Area of Plot" Width="238px" Font-Names="Arial" ForeColor="MidnightBlue">69 70 "txtPlotArea" runat="server" Width="205px">71 "dpePlotArea" runat="server"72 ServicePath="PlotAreaService.asmx"73 ServiceMethod="GetPlotArea"74 TargetControlID="txtPlotArea"75 ContextKey=""76 ClearContentsDuringUpdate="true"77 BehaviorID="dpePlotAreaID">787980

8182838485page code behind8687using System;88using System.Data;89using System.Configuration;90using System.Collections;91using System.Web;92using System.Web.Security;93using System.Web.UI;94using System.Web.UI.WebControls;95using System.Web.UI.WebControls.WebParts;96using System.Web.UI.HtmlControls;97using System.Data.OleDb;98using System.Data.SqlClient;99using System.Collections.Specialized;100using System.Workflow.Runtime;101using System.Workflow.Runtime.Hosting;102using AjaxControlToolkit;103104105public partialclass ApplicationForm : System.Web.UI.Page106// Use BasePage.cs as code file for parameter getting and107// access to Module.cs108//public partial class ApplicationForm : BasePage109{110protected void Page_Load(object sender, EventArgs e)111 {112113string strPlotNumberID ="ctl00_cphNOCMasterPage_cddPlotNo_ClientState";114//string strAreaNameID = cddAreaName.ID;115 // CascadingAreaName Id not the dropdown116string strAreaNameID ="ctl00_cphNOCMasterPage_cddAreaName_ClientState";117 ddPlotNumber.Attributes.Add("OnChange","return SelectFromDDL(" + strPlotNumberID +"," + strAreaNameID +" )");118 }119120121}122123124125web service code126127using System;128using System.Web;129using System.Collections;130using System.Collections.Specialized;131using System.Collections.Generic;132using System.Xml;133using System.Web.Services;134using System.Web.Services.Protocols;135using System.Data;136using System.Data.OleDb;137using System.Data.SqlClient;138using AjaxControlToolkit;139140/// <summary>141/// Summary description for PlotAreaService142/// </summary>143[WebService(Namespace ="http://tempuri.org/")]144[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]145[System.Web.Script.Services.ScriptService]146public class PlotAreaService : System.Web.Services.WebService147{148 string strConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=****data table name ******;Data Source=*** Database Server Instance name****";149 string strTableName = "dbo.sharjah_area_name";150 string fldAreaName = "area_name";151 string fldPlotNo = "area_plot_number";152 string fldAreaOfPlot = "area_of_plot";153154public PlotAreaService()155 {156157//Uncomment the following line if using designed components158 //InitializeComponent();159 }160161162/*************************************163 * Required by cascading drop down164 * parameter name and type should not be changed165 * ***********************************/166 [WebMethod]167public CascadingDropDownNameValue[] GetAreaName(string knownCategoryValues,string category)168 {169170 dsAreaNameTableAdapters.sharjah_area_nameTableAdapter objAreaNameAdapter =new dsAreaNameTableAdapters.sharjah_area_nameTableAdapter();171 List lstAreaName =new List();172173foreach (DataRow drAreaNameTempin objAreaNameAdapter.dtGetDataAreaName())174 {175string strAreaName = drAreaNameTemp[fldAreaName].ToString();176 lstAreaName.Add(new CascadingDropDownNameValue(strAreaName, strAreaName));177178 }179180return lstAreaName.ToArray();181 }182183 [WebMethod]184public CascadingDropDownNameValue[] GetPlotNo(string knownCategoryValues,string category)185186 {187string[] arrChosenAreaName = knownCategoryValues.Split(':',';');188string strChosenAreaName = arrChosenAreaName[1];189 dsPlotNoTableAdapters.sharjah_area_nameTableAdapter objPlotNoAdapter =new dsPlotNoTableAdapters.sharjah_area_nameTableAdapter();190 List lstPlotNo =new List();191foreach (DataRow drPlotNoin objPlotNoAdapter.dtPlotNoData(strChosenAreaName))192 {193string strPlotNo = drPlotNo[fldPlotNo].ToString();194 lstPlotNo.Add(new CascadingDropDownNameValue(strPlotNo, strPlotNo));195196 }197return lstPlotNo.ToArray();198 }199200 [WebMethod]201public string GetPlotArea(string contextKey)202 {203 System.Threading.Thread.Sleep(250);204string strPlotArea =string.Empty;205string[] arrContextKey = contextKey.Split(',');206string strAreaName = arrContextKey[0];207string strPlotNo = arrContextKey[1];208 dsPlotAreaTableAdapters.sharjah_area_nameTableAdapter objPlotAreaAdapter =new dsPlotAreaTableAdapters.sharjah_area_nameTableAdapter();209210foreach (DataRow drPlotAreain objPlotAreaAdapter.dtPlotAreaData(strAreaName, strPlotNo))211 {212 strPlotArea = drPlotArea[fldAreaOfPlot].ToString();213 }214return strPlotArea;215 }216}217218219220