473,657 Members | 2,415 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Databinding by ClientID

Hi,
I'm trying to learn ASP.NET by doing a pilot project:

I have a DataGrid which contains a nested DataList. I want to iterate
through the SQLDataReader for the DataGrid and populate each DataList
by binding to a fresh SQLDataReader. At the moment I can only bind to
the first instance of the DataList. If I could bind the data by the
ClientID (or UniqueID), I'm sure it would work. Is there a way of
doing this? Or maybe there is a better approach to getting nested data
from separate SQLDataReaders.

Here's the relevant part of the code with extraneous bits removed (I
hope the line breaks don't make it unreadable!):

// ######### ASPX ###########

<asp:DataGrid Border="1" Runat="server" Id="dgApplicant s">
<Columns>
<asp:BoundColum n DataField="Appl icantRef" Visible="False" />

<%-- Some more BoundColumns and TemplateColumns --%>

<asp:TemplateCo lumn>
<ItemTemplate >
<tr>
<td width="30px">&n bsp;</td>
<td colspan="8">
<asp:DataList Border="0" Runat="server" Id="dgApplicati ons"
AutoGenerateCol umns="False" Height="0px" Width="100%"
AllowSorting="F alse">
<ItemTemplate >
<b>App&nbsp;< %# DataBinder.Eval (Container.Data Item,
"VendorNo")%>&n bsp;<%# DataBinder.Eval (Container.Data Item,
"ApplicationRef ")%>&nbsp;v <%# DataBinder.Eval (Container.Data Item,
"Version")%>&nb sp;<%# DataBinder.Eval (Container.Data Item,
"Status")%> </b>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</asp:DataGrid>

// ######### ASPX ENDS ###########

// ######### CODE-BEHIND ###########
//adoApplicantRea der is the outer loop
//adoApplicationR eader is the inner loop

if(objDuplicate PartiesApplican t.ListParties(i nputSurname, inputTown,
inputMainCPH, inputBusinessNa me, inputPostcode, inputOrderBy, ref
adoApplicantRea der) == MyAssembly.AESI S.ReturnCodes.S uccess)
{
// OK, the SQL data layer object returned "success", but did we get
some results?
if(adoApplicant Reader.HasRows)
{
// successful search: hide prompt and display Update button
lblPrompt.Visib le = false;
btnUpdate.Visib le = true;

// databinding method
this.dgApplican ts.DataSource = adoApplicantRea der;
this.dgApplican ts.DataBind();
adoApplicantRea der.Close();

// with the firehose cursor (SQLDataReader) , we have to do the query
again after it is bound to pass it's members...
if(objDuplicate PartiesApplican t.ListParties(i nputSurname, inputTown,
inputMainCPH, inputBusinessNa me, inputPostcode, inputOrderBy, ref
adoApplicantRea der) == MyAssembly.AESI S.ReturnCodes.S uccess)
{
// SQL data layer object returned "success"
if(adoApplicant Reader.HasRows)
{
while (adoApplicantRe ader.Read())
{
int intOrd = adoApplicantRea der.GetOrdinal( "ApplicantRef") ;
int intApplicantRef = (int)adoApplica ntReader.GetVal ue(intOrd);

SqlDataReader adoApplicationR eader = null;

if(objDuplicate PartiesApplicat ion.ListPartyAp plications(intA pplicantRef,
ref adoApplicationR eader) == MyAssembly.AESI S.ReturnCodes.S uccess)
{
// did we get some results?
if(adoApplicati onReader.HasRow s)
{
// find a reference to the nested DataList
foreach(DataGri dItem dgItem in dgApplicants.It ems)
{

DataList dgSelected =
(DataList)dgIte m.FindControl(" dgApplications" );

// here I need to find the reference name of each nested
datagrid
// and assign data to that...
Response.Write( "<tr><td><f ont color=#cc0000>C lientID:
"+dgSelected.Cl ientID+"</font></td></tr>"); // debug
dgSelected.Data Source = adoApplicationR eader;
dgSelected.Data Bind();

}
}
adoApplicationR eader.Close();
}
}
}
}
else
{
lblPrompt.Text = "No records returned for this search. Please try
again.";
}
// tidy up before the garbage collector gets a chance to do it...
adoApplicantRea der.Close();
}
else
{
lblPrompt.Text = "DATABASE ERROR:<br/><font color=#ff0000>\ "" +
objDuplicatePar tiesApplicant.N ativeError + "\"</font><br/>Please
report this error to AESIS support.";
}
}
// ######### CODE-BEHIND ENDS ###########

The whole thing looks ugly to me because I have to keep on getting
fresh data, is there a more flexible cursor that I can use?

My next step is to investigate using DataSets, combining the XML DOMs
and doing all the manipulation of the presentation layer via
client-side JavaScript. Is this the recommended method?

Thanks,
oafyuf
Nov 17 '05 #1
1 2224
Hi Oafyuf,

You need to use the datagrid's ItemDataBound event to populate the inner
datalist. Here is a sample based on the Pubs sample database.

I placed a datagrid on a form and added a template column (the rest are
autogenerate). I added a datalist to the template column. Then I added the
following code.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
If Not IsPostBack Then
Bind()
End If
End Sub

Private Sub Bind()
Dim Qry1 As System.Data.Sql Client.SqlDataR eader
Dim connectionStrin g As String = "server='localh ost';
trusted_connect ion=true; Database='pubs' "
Dim sqlConnection As System.Data.Sql Client.SqlConne ction = New
System.Data.Sql Client.SqlConne ction(connectio nString)
Dim queryString As String = "SELECT au_id, au_lname, au_fname FROM
authors"
Dim sqlCommand As System.Data.Sql Client.SqlComma nd = New
System.Data.Sql Client.SqlComma nd(queryString, sqlConnection)
sqlConnection.O pen()
Qry1 =
sqlCommand.Exec uteReader(Syste m.Data.CommandB ehavior.CloseCo nnection)
DataGrid1.DataS ource = Qry1
DataGrid1.DataB ind()
Qry1.Close()
sqlCommand.Disp ose()
sqlConnection.C lose()
sqlConnection.D ispose()
End Sub

Private Sub DataGrid1_ItemD ataBound(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Data GridItemEventAr gs) Handles
DataGrid1.ItemD ataBound
If e.Item.ItemType = ListItemType.It em Or e.Item.ItemType =
ListItemType.Al ternatingItem Then
Dim list As ListBox
list = e.Item.Cells(0) .Controls(1)
Dim Qry1 As System.Data.Sql Client.SqlDataR eader
Dim connectionStrin g As String = "server='localh ost';
trusted_connect ion=true; Database='pubs' "
Dim sqlConnection As System.Data.Sql Client.SqlConne ction = New
System.Data.Sql Client.SqlConne ction(connectio nString)
Dim queryString As String = "SELECT title FROM titles t inner
join titleauthor ta on t.title_id = ta.title_id inner join authors a on
ta.au_id = a.au_id where a.au_id = '" & e.Item.Cells(1) .Text & "'"
Dim sqlCommand As System.Data.Sql Client.SqlComma nd = New
System.Data.Sql Client.SqlComma nd(queryString, sqlConnection)
sqlConnection.O pen()
Qry1 =
sqlCommand.Exec uteReader(Syste m.Data.CommandB ehavior.CloseCo nnection)
list.DataSource = Qry1
list.DataTextFi eld = "title"
list.DataBind()
If list.Items.Coun t = 0 Then list.Visible = False
list.Height = list.Height.Poi nt(30 * list.Items.Coun t)
Qry1.Close()
sqlCommand.Disp ose()
sqlConnection.C lose()
sqlConnection.D ispose()
End If
End Sub

---
I hope this helps.

Thank you, Mike
Microsoft, ASP.NET Support Professional

Microsoft highly recommends to all of our customers that they visit the
http://www.microsoft.com/protect site and perform the three straightforward
steps listed to improve your computer’s security.

This posting is provided "AS IS", with no warranties, and confers no rights.
--------------------
From: oa****@hotmail. com (oafyuf)
Newsgroups: microsoft.publi c.dotnet.framew ork.aspnet
Subject: Databinding by ClientID
Date: 24 Oct 2003 04:24:41 -0700
Organization: http://groups.google.com
Lines: 138
Message-ID: <ea************ **************@ posting.google. com>
NNTP-Posting-Host: 212.137.57.41
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
X-Trace: posting.google. com 1066994681 30561 127.0.0.1 (24 Oct 2003 11:24:41 GMT) X-Complaints-To: gr**********@go ogle.com
NNTP-Posting-Date: Fri, 24 Oct 2003 11:24:41 +0000 (UTC)
Path: cpmsftngxa06.ph x.gbl!TK2MSFTNG P08.phx.gbl!new sfeed00.sul.t-online.de!t-onlin
e.de!news-spur1.maxwell.s yr.edu!news.max well.syr.edu!po stnews1.google. com!no
t-for-mail Xref: cpmsftngxa06.ph x.gbl microsoft.publi c.dotnet.framew ork.aspnet:1862 90
X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet

Hi,
I'm trying to learn ASP.NET by doing a pilot project:

I have a DataGrid which contains a nested DataList. I want to iterate
through the SQLDataReader for the DataGrid and populate each DataList
by binding to a fresh SQLDataReader. At the moment I can only bind to
the first instance of the DataList. If I could bind the data by the
ClientID (or UniqueID), I'm sure it would work. Is there a way of
doing this? Or maybe there is a better approach to getting nested data
from separate SQLDataReaders.

Here's the relevant part of the code with extraneous bits removed (I
hope the line breaks don't make it unreadable!):

// ######### ASPX ###########

<asp:DataGrid Border="1" Runat="server" Id="dgApplicant s">
<Columns>
<asp:BoundColum n DataField="Appl icantRef" Visible="False" />

<%-- Some more BoundColumns and TemplateColumns --%>

<asp:TemplateCo lumn>
<ItemTemplate >
<tr>
<td width="30px">&n bsp;</td>
<td colspan="8">
<asp:DataList Border="0" Runat="server" Id="dgApplicati ons"
AutoGenerateCol umns="False" Height="0px" Width="100%"
AllowSorting="F alse">
<ItemTemplate >
<b>App&nbsp;< %# DataBinder.Eval (Container.Data Item,
"VendorNo")%>&n bsp;<%# DataBinder.Eval (Container.Data Item,
"ApplicationRef ")%>&nbsp;v <%# DataBinder.Eval (Container.Data Item,
"Version")%>&nb sp;<%# DataBinder.Eval (Container.Data Item,
"Status")%> </b>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</asp:DataGrid>

// ######### ASPX ENDS ###########

// ######### CODE-BEHIND ###########
//adoApplicantRea der is the outer loop
//adoApplicationR eader is the inner loop

if(objDuplicate PartiesApplican t.ListParties(i nputSurname, inputTown,
inputMainCPH, inputBusinessNa me, inputPostcode, inputOrderBy, ref
adoApplicantRea der) == MyAssembly.AESI S.ReturnCodes.S uccess)
{
// OK, the SQL data layer object returned "success", but did we get
some results?
if(adoApplicant Reader.HasRows)
{
// successful search: hide prompt and display Update button
lblPrompt.Visib le = false;
btnUpdate.Visib le = true;

// databinding method
this.dgApplican ts.DataSource = adoApplicantRea der;
this.dgApplican ts.DataBind();
adoApplicantRea der.Close();

// with the firehose cursor (SQLDataReader) , we have to do the query
again after it is bound to pass it's members...
if(objDuplicate PartiesApplican t.ListParties(i nputSurname, inputTown,
inputMainCPH, inputBusinessNa me, inputPostcode, inputOrderBy, ref
adoApplicantRea der) == MyAssembly.AESI S.ReturnCodes.S uccess)
{
// SQL data layer object returned "success"
if(adoApplicant Reader.HasRows)
{
while (adoApplicantRe ader.Read())
{
int intOrd = adoApplicantRea der.GetOrdinal( "ApplicantRef") ;
int intApplicantRef = (int)adoApplica ntReader.GetVal ue(intOrd);

SqlDataReader adoApplicationR eader = null;

if(objDuplicate PartiesApplicat ion.ListPartyAp plications(intA pplicantRef, ref adoApplicationR eader) == MyAssembly.AESI S.ReturnCodes.S uccess)
{
// did we get some results?
if(adoApplicati onReader.HasRow s)
{
// find a reference to the nested DataList
foreach(DataGri dItem dgItem in dgApplicants.It ems)
{

DataList dgSelected =
(DataList)dgIte m.FindControl(" dgApplications" );

// here I need to find the reference name of each nested
datagrid
// and assign data to that...
Response.Write( "<tr><td><f ont color=#cc0000>C lientID:
"+dgSelected.Cl ientID+"</font></td></tr>"); // debug
dgSelected.Data Source = adoApplicationR eader;
dgSelected.Data Bind();

}
}
adoApplicationR eader.Close();
}
}
}
}
else
{
lblPrompt.Text = "No records returned for this search. Please try
again.";
}
// tidy up before the garbage collector gets a chance to do it...
adoApplicantRea der.Close();
}
else
{
lblPrompt.Text = "DATABASE ERROR:<br/><font color=#ff0000>\ "" +
objDuplicatePar tiesApplicant.N ativeError + "\"</font><br/>Please
report this error to AESIS support.";
}
}
// ######### CODE-BEHIND ENDS ###########

The whole thing looks ugly to me because I have to keep on getting
fresh data, is there a more flexible cursor that I can use?

My next step is to investigate using DataSets, combining the XML DOMs
and doing all the manipulation of the presentation layer via
client-side JavaScript. Is this the recommended method?

Thanks,
oafyuf


Nov 17 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7031
by: John | last post by:
Hello all, I'm trying to display a dataset into a datagrid and format the datagrid columns but I'm having a hard time with it. I've tried the MSDN examples but they don't seem to work. Basically, what I want to do is that, on a button click, the dataset fills up dynamically, binds to the datagrid, and displays the data. This is my code: mySql = "select itemID, OrderDate " +
1
2511
by: Maras | last post by:
Hello, as we know VB is not case sensivity. I have a following problem, I have to send to another server few parametrs by post or get method, one of them MUST be a "clientID", it's preety simple, but in VB .NET there is a property ClientID and I get an error, a conflict beetwen my clientID and ClientID of MyBase class aspx code: ****
2
1907
by: kw | last post by:
TextBox t=new TextBox(); Controls.Add(t); t.ID=t.ClientID; //reads: "_MyControl1__ctl16" And even in OnPreRender, I examine the Controls collection and verify that the ID of the TextBox is "_MyControl1__ctl16". But then, on the final HTML rendered, if you look at the page, the textbox looks like this:
25
4055
by: Neo Geshel | last post by:
This works: <form> <asp:TextBox id="name" /> <%= name.ClientID %> </form> But this DOES NOT work: <form>
2
1503
by: Neo Geshel | last post by:
After pouring over about a dozen sites that clearly dealt with ClientID all by itself, I came to the realization that about 2/3+ of them were doing it wrong. It is indeed impossible to grab the Client ID of a form field from within a DataGrid like this: <%= FormFieldID.ClientID %>. At least, not without extra work. How did I do this? I created a new DataGrid from scratch, with a form above it and a form inside of it. This was a page...
2
1769
by: JJ | last post by:
Hi, Can anyone advise me how is the ClientID issued? I had a suite Controls which consist of a context menu (i.e. a group of tables, rows and cells situated in a class library) and a set of buttons. I am doing dynamic HTML which I only know how many buttons and context menu to create on the fly. Next I had written a simple JAvascript which will allow the dialogs (i.e. the context menu's tables) to be placed at the correct location when
0
1407
by: Swetha | last post by:
Hello I have a FormView with InsertItem, EditItem and ItemTemplates. Depending on from where the page is accessed, the page opens up in either Insert, Edit or ReadOnly mode. The FormView is databound. The problem I have is when the page opens up in Insert Mode. I require one of the fields to be populated with a databound field, but for some some reason this doesnt happen in the InsertMode. Following is the FormView:
9
24784
by: J055 | last post by:
Hi I have a very simple configuration of the GridView with paging and sorting. When I do a postback the DataBinding event fires twice - in both the ProcessPostData and PreRender stages of the page life cycle. In this example the event fires twice when a) GridView EnableViewState=False and any image type control in the <columns/> element. When either EnableViewState is set to true or the image button is removed, the event fires once....
2
6750
by: DC | last post by:
Hi, I am doing something like this in the ItemCreated event (ASP.Net 1.1): DataGridItem pagerRow = e.Item; TableCell pagerCell = pagerRow.Cells; Control addedControl = new Control(); addedControl.ID = "addedControl"; pagerCell.Controls.Add(addedControl);
0
8413
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.