Showing posts with label 2nd. Show all posts
Showing posts with label 2nd. Show all posts

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

Problem in Cascading Drop Down

I have created a website using Cascading DropDown in AJAX control tool kit......

I have 3 DropDown lists.....and the list in 2nd one is populated when an Item from 1st DropDown List is selected...Similarly 3rd DropDown is populated depending on 2nd list.....

My problem is that I get all my values in dropdown 3 list but I wanted to show the whole list of items in my result.....means suppose at the end of the selection I have 3 items in DropDown list 3 then all the items in tat list shud be my result......

can u tell me how to extract tat all the items from DropDown list 3 and display it.....

Hi Hemil,

Based on my understanding, there are three DropDownlists in the page. The second DropDownList is bound according the item selected in the first DropDownList. The third DropDownList is bound according the item selected in the second DropDownList. Now you want to know how to get all the items of third DropDownList. In one word, you want to know how to get a DropDownList's items. If I have misunderstood you, please feel free to let me know.

To get all the items of DropDownList, you should use loop to get them.

To better understand your question, could you please confirm the following information:

If you want to get the value of item, the code should like as follows:

string strResult ="";foreach (ListItem itemin DropDownList1.Items) { strResult += item.Value; } 


Ya u got my problem rite but only thing is that I have all the items in Drop Down list 3 which is populated according to the Items selected from Drop Down1 and Drop Down2.....

So after selecting items from DropDown 1 and 2 I get my result in Drop down 3 Which I need to display all at once.....means all items in drop Down list 3.....

So watever code U gave me will work or no and if yes will it work if i change the item in Drop Down 1 or 2 accordingly Dropdown 3 will change so will it append to the Display result.......I have used Cascading Dropdown of AJAX Control tool kit......

<ajaxToolkit:ToolkitScriptManager ID="ScriptManager1" runat="server" /
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server"
ServiceMethod="GetDropDownContents"
UseContextKey="True"
Category="major"
LoadingText="[Loading majors...]"
PromptText="Degree Major/ Program Name"
ServicePath="MajorsDatabase.asmx"
TargetControlID="DropDownList1">
</ajaxToolkit:CascadingDropDown>

<br /><br />

<asp:DropDownList ID="DropDownList2" runat="server"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>

<ajaxToolkit:CascadingDropDown ID="CascadingDropDown2" runat="server"
ParentControlID="DropDownList1"
Category="type"
ContextKey="[Loading major types...]"
PromptText="Degree Major/ Program Type"
ServiceMethod="GetDropDownContents"
ServicePath="MajorsDatabase.asmx"
TargetControlID="DropDownList2">
</ajaxToolkit:CascadingDropDown
<br /><br /
<asp:DropDownList ID="DropDownList3" runat="server"
OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" Visible="true">
</asp:DropDownList>

<ajaxToolkit:CascadingDropDown ID="CascadingDropDown3" runat="server"
ParentControlID="DropDownList2"
Category="campus"
ContextKey="[Loading campus names...]"
PromptText="Campus"
ServiceMethod="GetDropDownContents"
ServicePath="MajorsDatabase.asmx"
TargetControlID="DropDownList3">
</ajaxToolkit:CascadingDropDown>


Hi Hemil,

The code I posted above is only a simple example, which tells you how to loop the DropDownList. You can use different way to display the result according your requirements.

I hope this helps.


Sir,

I tried implementing ur code but I get only the value which is selected item in Drop Down instead of all the values in DropDown List 3......

I will tell you something more on this...I want to display the result after I select Item in Drop Down List 2.......means as soon as I select one item from Drop Down List 2 and then I should press Submit button so It should give me all the values contained in Drop Down list 3 which I will make Invisible to the user.....So in short there is dropDown list behind the scenes which has all the values in DropDown list........I want to display all the Items in dropdown list 3........after I press Submit button......

So the sequence of operations will be.....

1. Select one item from DropDownlist 1

2. As per the selection in dropdown list 1, Drop Downlist 2 will be populated with values so Select item from drop down List 2.

3. Now behind the scenes I have drop down list 3 but I dunt want to show the DropDown....it has all the Items which I need to display to the user...

4. There is one Submit button which I have to press and it should show all the Items from Drop DOwn list 3...which is present behind the scenes...

Thanks,

hemil.



Hi Hemil,

Thanks for your response.

Based on my understanding about your response above, you should bind the DropDownList3 and then loop this DropDownList3 to display Values in the Button event.

The code of Button event should like as follows:

protected void Button1_Click(object sender, EventArgs e) {//Bind DropDownList3 by the item selected in the DropDownList2 DropDownList3.DataSource = YourDataSource; DropDownList3.DataTextField ="DisplayField"; DropDownList3.DataValueField ="ValueField"; DropDownList3.DataBind();string strResult ="";//loop DropDownList3foreach (ListItem itemin DropDownList3.Items) { strResult += item.Value; } }


I hope this helps.


Hi Hemil,

If you have any question, please post them here and don't need to email me directly. We are glad to help you. If you post the question here, other kindly people will help you too. Thanks for your understanding.

Based on your question and the codes you sent to me, you cannot bind the XML file to DropDownList directly. You should read the XML file to a DataSet or XmlDataSource and bind the DropDownList with the data source.

The code should like as follows:

<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList3" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile.xml"></asp:XmlDataSource>

</div>
</form>

protected void Button1_Click(object sender, EventArgs e) { XmlDataSource1.XPath ="/MajorsDatabase/major/type";// Use xpath to filter data you want to display. DropDownList3.DataSource = XmlDataSource1; DropDownList3.DataTextField ="name"; DropDownList3.DataValueField ="name"; DropDownList3.DataBind(); }

I hope this helps.


The code is working ... Thanks ...

But I am facing a new problem ... which is ,.... when I select the first and second drop down box .. I get all the names of the campuses ... where as ... it should display me only campus names depending on the DDL1 and DDL2 selection ...

i.e. DDL => DropDownList

When I select from DDL1 - "Acturial Science"

and DDL2 - "b" ... it should give me only ... Campus Name as "San Jose" and "San Diego".

but it is giving all the Campus name from the XML file under the tag "campus" ...

Is there any way we can query the DataBinding or DataSource ...

Thanks.....


Hi Hemil,

You should add XPath to filter the data you want to display.

For example, If you want to get the type names, which are the child node of major node and this major node's name property is "Advertising", the XPath should like as follow:
XmlDataSource1.XPath = "/MajorsDatabase/major[@.name='Advertising']/type";

So you can write the XPath to filter the data. For more information, seeXmlDataSource.XPath Property.


I hope this helps.


Good Afternoon,

Thanks a lot for the guidance... the code works just perfect for the Static values.

I would like to ask you few things like ...

1. can we pass dynamically selected arguments in Xpath ?

2. do we need to write a query for this dynamic invocation ?

I was trying ...

XmlDataSource1.XPath ="/MajorsDatabase/major [DropDownList1.SelectedItem.Text] /type[DropDownList2.SelectedItem.Text]/campus";

But is is not working ...

As we are selecting Major from DDL1 and Type from DDL2 ... I would like to pass those dynamically selected values in XPath ....

I was also trying ...

int one = 1, two = 1;

XmlDataSource1.XPath ="/MajorsDatabase/major[one] /type[two]/campus"; ====> Not working ... where as if we write

XmlDataSource1.XPath ="/MajorsDatabase/major[1] /type[1]/campus"; ====> works ...

Thanks Again ...


Hi Hemil,

Yes, we can pass parameters to XPath dynamically and easy. Since the parameters are variables, we cannot write them in the XPtah string directly. We should use plus to connect the XPath and parameters.

For example:

string strParameter ="Advertising"; XmlDataSource1.XPath ="/MajorsDatabase/major[@.name='"+strParameter+"']/type";


I hope this helps.


Thanks very much for all your help.

Code is working fine.