Showing posts with label values. Show all posts
Showing posts with label values. Show all posts

Wednesday, March 28, 2012

Posting from Tab Control does not work

Hi all,

I am new to AJAXtoolkit and I tried the following code it runs fine but does not input values in textbox nor updates the image

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function PanelClick(sender, e) {
}

function ActiveTabChanged(sender, e) {
__doPostBack('<%= Tabs.ClientID %>', sender.get_activeTab().get_headerText());
}
</script>
<div>
<ajaxToolkit:TabContainer runat="server" ID="Tabs" Height="150px"
OnClientActiveTabChanged="ActiveTabChanged"
OnActiveTabChanged="ActiveTabChangedServer">
<ajaxToolkit:TabPanel runat="Server" ID="Panel1" HeaderText="Tab One">
<ContentTemplate>
PAGE ONE - Sample HTML Content for Tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel runat="Server" ID="Panel2" HeaderText="Tab Two" >
<ContentTemplate>
PAGE TWO - Sample HTML Content for Tab
</ContentTemplate>
</ajaxToolkit:TabPanel>

<ajaxToolkit:TabPanel runat="Server" ID="Panel3" OnClientClick="PanelClick" HeaderText="Tab Three">
<ContentTemplate>
PAGE THREE - Sample HTML Content for Tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer> <br />
<asp:Image ID="Image1" runat="server" />
<asp:TextBox ID="txtTabSelect" runat="server" />
</div>
</form>

in the code behind I have this:

protected void Page_Load(object sender, EventArgs e)
{
ScriptManager1.RegisterAsyncPostBackControl(Tabs);
}

protected void ActiveTabChangedServer(object sender, EventArgs e)
{
if (Tabs.ActiveTab == Panel1)
{
Image1.ImageUrl = "~/Images/HomeEnabled.jpg";
txtTabSelect.Text = "Selected Panel 1";

}

if (Tabs.ActiveTab == Panel2)
{
Image1.ImageUrl = "~/Images/ProductsEnabled.jpg";
txtTabSelect.Text = "Selected Panel 2";
}

if (Tabs.ActiveTab == Panel3)
{
Image1.ImageUrl = "~/Images/SupportEnabled.jpg";
txtTabSelect.Text = "Selected Panel 3";
}

}

Please do tell me what am I doing wrong. I tried debugging, the watch shows that the values are present but do display.
Thanks,

do you have the autopostback property on the tabs container set to true?


Hi,

ajaxToolkit:TabContainer does not have the property and I did try adding AutoPostBack="true", compiled it and ran but it still does not work. what baffles me is it calls the

protected void ActiveTabChangedServer(object sender, EventArgs e)
{
.....

}

on the server and I can see the values in the watch window but when the page reloads, the values are not there

I have this in the page load event

if (!Page.IsPostBack)
{
ScriptManager1.RegisterAsyncPostBackControl(Tabs);
}

Thanks,


Hi,

It's caused by not calling __dopostback method in a correct way. I suggest using a hidden button to trigger postback. Here is a sample:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">protected void Page_Load(object sender, EventArgs e) { //ScriptManager1.RegisterAsyncPostBackControl(Tabs); } protected void ActiveTabChangedServer(object sender, EventArgs e) { if (Tabs.ActiveTab == Panel1) { Image1.ImageUrl = "~/Images/HomeEnabled.jpg"; txtTabSelect.Text = "Selected Panel 1"; } if (Tabs.ActiveTab == Panel2) { Image1.ImageUrl = "~/Images/ProductsEnabled.jpg"; txtTabSelect.Text = "Selected Panel 2"; } if (Tabs.ActiveTab == Panel3) { Image1.ImageUrl = "~/Images/SupportEnabled.jpg"; txtTabSelect.Text = "Selected Panel 3"; } //Response.Write(DateTime.Now.ToString()); } </script><html xmlns="http://www.w3.org/1999/xhtml" ><head id="Head1" runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <script type="text/javascript"> function PanelClick(sender, e) { } function ActiveTabChanged(sender, e) { $get("<%= Button1.ClientID%>").click();// __doPostBack('<%= Tabs.ClientID%>', sender.get_activeTab().get_headerText()); } </script> <div><asp:Button runat="server" style="display:none;" Text="Button" ID="Button1"></asp:Button> <ajaxToolkit:TabContainer runat="server" ID="Tabs" Height="150px" OnClientActiveTabChanged="ActiveTabChanged" OnActiveTabChanged="ActiveTabChangedServer"> <ajaxToolkit:TabPanel runat="Server" ID="Panel1" HeaderText="Tab One"> <ContentTemplate> PAGE ONE - Sample HTML Content for Tab </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel runat="Server" ID="Panel2" HeaderText="Tab Two" > <ContentTemplate> PAGE TWO - Sample HTML Content for Tab </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel runat="Server" ID="Panel3" OnClientClick="PanelClick" HeaderText="Tab Three"> <ContentTemplate> PAGE THREE - Sample HTML Content for Tab </ContentTemplate> </ajaxToolkit:TabPanel> </ajaxToolkit:TabContainer> <br /> <asp:Image ID="Image1" runat="server" /> <asp:TextBox ID="txtTabSelect" runat="server" /> </div> </form></body></html>

Hi Raymond Wen,

I tried your approach too.. but the error occurs again.

It gives me "Microsoft JScript runtime error: 'this.get_element().style' is null or not an object". I dont know what it is and why does it occur as I have not written this piece of code.

upon using a debugger it shows as this "this.get_element().style.visibility = 'visible';" which is present in the

_app_onload funtion like this:

_app_onload : function(sender, e)
{

.... this.get_element().style.visibility = 'visible';

}

Thanks for you help,
Stephen


Can you create a simple page to reproduce it?

Monday, March 26, 2012

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 displaying values in gridview using ajax

hi

I am using asp.net 2.0 version.and sql2005 database.

On my UpdateErrorLog.aspx page i have three dropdown.2nd dropdown is filled on basis of first and 3rd dropdown is filled on basis of second.On 3rd dropdown "onchange" event i have called javascript function"FetchDGContents()" defined in "AjaxScript.js" file using ajax.Ajax Request is send to page"AjaxServer.aspx" and i get the response from that page.Problem is coming when i am trying to use that response to display the data in gridview.Below i am writing the code for Ajax page,Design page and the javascript file.Error is mentioned in javascript file in FunctionFilltable() andCleartable().I have searched and found ,that the control name on page rendering is prefixed with its container name.So u can see in my code and in Javascript file the prefixed name is'ctl00_contentarea'.It is working fine for Dropdowns when i am accessing their values(below in code file u can see) but failed to do so for Gridview.Plz help me out.

Thanks is advance

Below Code ofUpdateErrorLog.aspx file-------

<%@dotnet.itags.org.PageLanguage="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeFile="UpdateErrorLog.aspx.cs"Inherits="UpdateErrorLog"Title="Untitled Page" %>

<asp:ContentContentPlaceHolderID="contentarea"Runat="Server">

<scriptsrc="js/filldropdown.js"type="text/javascript"></script>

<scriptsrc="js/AjaxScript.js"type="text/javascript"></script>//This is the file in which Prblem is coming

<divid="Headingtxt"class="containerheading">

Update Error Log</div>

<divid="formcontent"class="containerdiv">

<tablecellpadding="0"cellspacing="0"class="labelfont">

<tr>

<tdstyle="width: 65px; height: 30px">

<asp:LabelID="Label1"runat="server"Font-Names="Arial"Font-Size="X-Small"

Text="Project"></asp:Label></td>

<tdstyle="width: 100px; height: 30px">

<asp:DropDownListID="ProjectDropDown"runat="server"Width="179px">

</asp:DropDownList></td>

</tr>

<tr>

<tdstyle="width: 65px; height: 29px">

<asp:LabelID="Label2"runat="server"Font-Names="Arial"Font-Size="X-Small"

Text="WBS"></asp:Label></td>

<tdstyle="width: 100px; height: 29px">

<asp:DropDownListID="WBSDropDown"runat="server"Width="178px">

</asp:DropDownList></td>

</tr>

<tr>

<tdstyle="width: 65px; height: 34px;">

<asp:LabelID="Label3"runat="server"Font-Names="Arial"Font-Size="X-Small"

Text="Task"Width="32px"></asp:Label></td>

<tdstyle="width: 100px; height: 34px;">

<asp:DropDownListID="TaskDropDown"runat="server"Width="178px">

</asp:DropDownList></td>

</tr>

<tr>

<tdstyle="width: 65px; height: 28px">

</td>

<tdstyle="width: 100px; height: 28px"align="left">

<asp:ButtonID="BtnGo"runat="server"Text="Go"Width="47px"/></td>

</tr>

</table>

</div>

<divid="gridviewcontent"style="left: 175px; width: 515px; position: absolute; top: 265px;

height: 84px">

<asp:GridViewid="gverrorlog"style="Z-INDEX: 102; LEFT: -6px; POSITION: absolute; TOP: 1px"runat="server"

width="592px"CellPadding="3"GridLines="Both"BorderStyle="Inset"Font-Names="Arial"Font-Size="X-Small"Height="100px">

<HeaderStyleCssClass="colhead"BackColor="#FF8080"Font-Names="Arial"Font-Size="X-Small"></HeaderStyle>

<RowStyleBackColor="#FFC0C0"Font-Names="Arial"Font-Size="X-Small"/>

</asp:GridView>

<TABLEid="imgtbl"style="VISIBILITY:hidden"borderColor="#000000"cellSpacing="1"cellPadding="1"

width="96"bgColor="#ffffff"border="0">

<TR>

<TD></TD>

</TR>

</TABLE>

</div>

</asp:Content>

-------------------------------------------

Code forAjaxserver.aspx page----------

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;

using System.Data.SqlClient;

publicpartialclassAjaxServer : System.Web.UI.Page

{

#region Variables

SqlConnection con =newSqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

CommonClass objcommon =newCommonClass();

ErrorLogClass objerrlog=newErrorLogClass();

DataSet SelectLogDS =newDataSet();

string chString;

#endregion

protectedvoid Page_Load(object sender,EventArgs e)

{

if (!IsPostBack)

{

//getting querystring value from update errorlog page

string pid = Request.QueryString["PID"];

string wbsid = Request.QueryString["WBSID"];

string tid = Request.QueryString["TID"];if(Request.QueryString["FromUperrpage"]!=null)

{

Response.Clear();

SelectLogDS=objerrlog.SelectErrorLog(pid, wbsid, tid); //SelectErrorLog is the method defined in a class.

//If you want to test by showing the "Image for Process" for a long time, uncomment the below two lines and set the time

//Dim th As System.Threading.Thread

//th.Sleep(200)

chString = SelectLogDS.GetXml();

Response.Clear();

Response.ContentType ="text/xml";

Response.Write(chString);

Response.End();

}else

{

Response.Clear();

Response.End();

}

}

else

{

Response.Clear();

Response.End();

}

}

}

-----------------------------------

Code forAjaxScript.js ------------------------

// This creates a XMLRequest (ActiveXObject) to be sent to the server

var XmlReq;

function CreateXmlReq()

{

try

{

XmlReq =new ActiveXObject("Msxml2.XMLHTTP");

}

catch(e)

{

try

{

XmlReq =new ActiveXObject("Microsoft.XMLHTTP");

}

catch(oc)

{

XmlReq =null;

}

}

if(!XmlReq &&typeof XMLHttpRequest !="undefined")

{

XmlReq =new XMLHttpRequest();

}

}

//This fucntion is to send the choice into the AJAX Server page for processing

function FetchDGContents()

{

//Starts displaying the Process Image table

imgtbl.style.visibility ='visible';var requestUrl ="AjaxServer.aspx?FromUperrpage=true&PID=" + document.getElementById("ctl00_contentarea_ProjectDropDown").value +"&WBSID=" + document.getElementById("ctl00_contentarea_WBSDropDown").value +"&TID=" + document.getElementById("ctl00_contentarea_TaskDropDown").value;

CreateXmlReq();

if(XmlReq)

{

XmlReq.onreadystatechange = HandleResponse;

XmlReq.open("GET", requestUrl,true);

XmlReq.send();

}

}

function HandleResponse()

{

if(XmlReq.readyState == 4)

{

if(XmlReq.status == 200)

{

// Before filling new contents into the DataGrid, clear the cotents by calling this function

//ClearTable();

// Fill the cleared Datagrid with new XML Reponse

FillTable(XmlReq.responseXML.documentElement);

// Hides the Process Image Table after displaying the contents

imgtbl.style.visibility ='hidden';

}

else

{

alert("There was a problem retrieving data from the server." );

}

}

}

//Fills the datagrid contents with the newly recieved Response content

function FillTable(serrorlog)

{

// Gets the response XML

var errlog = serrorlog.getElementsByTagName('NewDataSet');

// Gets the table type content present in the Response XML and gets the data into a variable tbl

var tbl = document.getElementById('ctl00_contentarea_gverrorlog').getElementsByTagName("tbody")[0];//Getting Error on this Line Error is: "Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object"

// Iterate through the table and add HTML Rows & contents into it.

for(var i=0;i<errlog.context.childNodes(0).parentNode.childNodes.length;i++)

{

// Create a HTML Row

var row = document.createElement("TR");

// Set the style

row.setAttribute("className","text");row.setAttribute("bgColor","#ECECEC");

// Iterate thorugh the columns of each row

for(var j=0;j<errlog.context.childNodes(0).childNodes.length;j++)

{

// Create a HTML DataColumn

var cell = document.createElement("TD");

// Store the cotents we got from Response XML into the column

cell.innerHTML = errlog.context.childNodes(i).childNodes(j).text;

// Append the new column into the current row

row.appendChild(cell);

}

// Append the current row into the HTML Table(i.e DataGrid)

tbl.appendChild(row)

}

}

// Clearing the existing contents of the Datagrid

function ClearTable()

{

var tbl = document.getElementById('ctl00_contentarea_gverrorlog').getElementsByTagName("tbody")[0]; //Getting Error on this Line Error is: "Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object"

var row = tbl.rows.lengthfor (var i=1,j=1;j<row;i++,j++)

{

if (tbl.rows.length == 2){i = 1;}

tbl.deleteRow(i);

if (tbl.rows.length == i) {i = 0;}

}

}

-----------------------------------

u cant access objects of a page by id in separate javascript file

try palacing the code in the aspx page in <Script> tag or

u need to send object of that control to javascript function


Its also not working if we write the code in aspx page instead of placing in seperate js file.

I am still getting same error.

thanks


document.getElementById('ctl00_contentarea_gverrorlog').

instead try using

document.getElementById('<%=Controlid.clientid %>').

i think Controlid is contentarea_gverrorlog


can you please tell me what is clientid in the above code?

i have tried using document.getElementById('<%=Controlid.clientid %>'). but same error is coming.At runtime

it is showing this statement as "document.getElementById('System.Web.UI.WebControls.GridView')"

thanks


Client Id is id of that contol on client side like "ct100_gridview1"

use like this if u have a problem

in javascript which is in the same aspx page that has control

document.getElementById('<%= Id %>').

and Code behind like this

publicpartialclassDisabling_controls : System.Web.UI.Page

{

//Declare Page level global variable

Public String Id=String.Empty;

protectedvoid Page_Load(object sender,EventArgs e)

{

Id = GridView1.ClientID.ToString();

}


Your suggested code is working fine.but still error is coming on the same line i.e

----var tbl = document.getElementById('<%= Id %>').getElementsByTagName("tbody")[0];

if i remove "getElementsByTagName("tbody")[0]" i get the varaible "tbl" valuenull and If I don' t remove

i get the above said error.I am unable to track why error is coming because this code is working fine

in .Net 1.0 version using datagrid.No solution till now...

this is the function in which error is coming...

function FillTable(serrorlog)

{

// Gets the response XML

var errlog = serrorlog.getElementsByTagName('TestErrorLog');

// Gets the table type content present in the Response XML and gets the data into a variable tbl

var tbl = document.getElementById('<%= Id %>').getElementsByTagName("tbody")[0];

// Iterate through the table and add HTML Rows & contents into it.

for(var i=0;i<errlog.context.childNodes(0).parentNode.childNodes.length;i++)

{

// Create a HTML Row

var row = document.createElement("TR");

// Set the style

row.setAttribute("className","text");row.setAttribute("bgColor","#ECECEC");

// Iterate thorugh the columns of each row

for(var j=0;j<errlog.context.childNodes(0).childNodes.length;j++)

{

// Create a HTML DataColumn

var cell = document.createElement("TD");

// Store the cotents we got from Response XML into the column

cell.innerHTML = errlog.context.childNodes(i).childNodes(j).text;

// Append the new column into the current row

row.appendChild(cell);

}

// Append the current row into the HTML Table(i.e DataGrid)

tbl.appendChild(row)

}

}


see view source to check whether datagrid is rendered with

tbody

tags for which you are searching


I m using gridview .In starting i have mentioned that i m working in .Net 2005.

in .Net 2003 the same code is working fine for datagrid.But as in .Net2005 i m using master

pages and therefore control name on rendering gets changed(which is not so in .Net2003).

Same code work fine in .Net2005 if i dont use master pages in my project.

thanks


hi

i got it! where the problem is.Problem i am not showing data in gridview on pageload that's why

the error is coming, because gridview is not rendered onpageload and i am trying to access it...

But then next problem is How to Do paging,sorting,and to define userdefined tempaltes if we use AJAX.

If there is some solution realted to this please give me.I m working in .Net 2005(gridview control).

thanks a lot for all ur help.


That's why i have asked u to see ViewSource whether it is rendered or not