473,854 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Handling data relations in Gridview

Hi - This could be a simple question. When I relate two tables in a
datasetet, how do I get that relation to show up in a GridView? The
only way I've done it, is to create a separate table in the dataset
with a join query for the GetData() select method. I use
ObjectDataStore to couple the GridView with the table adapter on the
dataset. If I point the ODS at the child table, the GridView will bind
to the "normal" select and I end up with the foreign keys displayed
verses the field in the parent table. That is the same thing that
happens with no relation.

What I end up doing is having a dataset with the parent and child as
unrelated tables w/ seperate adapters. I add a new table that is the
related data built via the join query. Since the update, insert,
delete methods can't be automatically created with this type table, I
create them myself and use the stuff passed in (the joined table row)
to update the child table.

I'd be happy to pass the FK to the gridview and let a bound control
figure out what to display from the parent table based on the child
table FK, but I haven't figured out how to do that with a Label.

TIA

Bill

Jun 8 '06 #1
5 6462
Hello Bill,

Welcome to the ASPNET newsgroup.

From your description, you're building a data display page in ASP.NET
application(2.0 ). Currently you have
a Dataset that contains multiple datatables which have relationship with
eachother, however, when bind a certain datatable in the dataset to a
Gridview, you found the gridview only display one dimension data only (with
out the related parent table's values) and you're wondering how to make the
GridView display the related table's data(through the foreign key column),
correct? If there is anything I missed or didn't quite address, please feel
free to let me know.

Based on my understanding, the behavior yet is expected due to the ASP.NET
webform page's databinding mechanism. ASP.NET template control databinding
is quite different from winform control databinding. In winform, since the
datasoure is always in memory, the databound context is easy to track the
datasource and navigate between the current bound datatable to its related
parent or child table. However, in ASP.NET since the page must be flushed
and write out to clent, it can not hold the datasource in memory forever,
it just query the current attached datasource(tabl e or view) and bind that
direct attached table/view's data/columns to the databound
control(Gridvie w, datagrid ....). that's why you'll find GridView directly
display the foreign key value rather than the detailed value in
parent/child table/view.

To resolve this in webform page, we need to manually customize the
databinding process. for example, we can use the databound control such as
GridView's Item/Row DataBound event to do the customization.
#GridView.RowDa taBound Event
http://msdn2.microsoft.com/en-us/lib...trols.gridview.
rowdatabound.as px

In the RowDataBound event, we can access the current GridView Row's inner
sub controls(in each gridviewRow column). Also, we can access the current
databound data item(such as DataRowview). Then, we can manualy get the
related data (parent or sub rows through the DAtaRowView) and use it to
modify the certain Gridview row column's controls. for example:
the following Gridview is bound to a DataView(from a datatable which
contains the Northwind "products" table's data), and the container dataset
also contains another datatable ("categories " table in northwind), I add a
relation between them and bind the products view to the GridView. In the
RowDataBound event, I manually query parent row data from Categories table:
=====aspx template======= ===

<asp:GridView ID="GridView1" runat="server" AutoGenerateCol umns="False"
OnRowDataBound= "GridView1_RowD ataBound">
<Columns>
<asp:BoundFie ld DataField="Prod uctID"
HeaderText="Pro ductID" />
<asp:BoundFie ld DataField="Prod uctName"
HeaderText="Pro ductName" />
<asp:TemplateFi eld HeaderText="Cat egory">
<EditItemTempla te>
<asp:TextBox ID="txtCategory " runat="server"
Text='<%# Bind("CategoryI D") %>'></asp:TextBox>
</EditItemTemplat e>
<ItemTemplate >
<asp:Label ID="lblCategory " runat="server"
Text='<%# Bind("CategoryI D") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateFie ld>
</Columns>
</asp:GridView>

==============c ode behind========= =====

protected void Page_Load(objec t sender, EventArgs e)
{
if (!IsPostBack)
{
PerformDataBind ();
}
}

protected void PerformDataBind ()
{
//get the dataset which contains two datatables that have relation
DataSet ds = GetDataSet();

ds.Relations.Ad d("products_cat egories",
ds.Tables[1].Columns["CategoryID "], ds.Tables[0].Columns["CategoryID "]);
GridView1.DataS ource = ds.Tables[0].DefaultView;

GridView1.DataB ind();
}
protected void GridView1_RowDa taBound(object sender, GridViewRowEven tArgs e)
{
if (e.Row.RowType == DataControlRowT ype.DataRow)
{
DataRowView product = e.Row.DataItem as DataRowView;

string strCategory =
product.Row.Get ParentRow("prod ucts_categories ")["CategoryNa me"] as string;

Label lbl = e.Row.FindContr ol("lblCategory ") as Label;

lbl.Text = strCategory;
}
}

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

Hope this helps. If you have anything unclear on this, please feel free to
post here.

Regards,

Steven Cheng
Microsoft Online Community Support
=============== =============== =============== =====

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Jun 9 '06 #2
Hi

Thanks for a very thorough response. You have hit the proverbial nail
on the head, understanding my "problem" exactly. Your experience on
the newsgroups is finally paying dividends I see (ha ha).

Anyway, though I understand your answer and your proposed workaround, I
can't say that I like it. I guess the alternative to achieving the
same functionality is to use stored procedures for the CRUD interface
but ... you lose the caching from the dataset, Correct? So if I had a
child row of 1000 items that each had a relation or two that mapped a
FK into a readable tag (city name vs an index), would I have to go back
to the DB through a tableadapter query "select city_name from citylist
(where index = @index)" or would I have the name of the city as part of
the join 1000 times (if the child records all came from the same city)?
There is something slightly annoying about both of these.

Are there any other options? The one I outlined below is interesting,
but it seems you are getting the same data twice. If I could some how
Fill()'s for the two related tables (two fills thru two table
adapters), then build a third table from the cached tables to satisfy
the relation .... Am I insane or is there something missing from the
FW?

A custom BL would still have to pass back a joined table by "doing" the
relation in the Get method. Is this a bad thing too?

Thanks again

Bill

Steven Cheng[MSFT] wrote:
Hello Bill,

Welcome to the ASPNET newsgroup.

From your description, you're building a data display page in ASP.NET
application(2.0 ). Currently you have
a Dataset that contains multiple datatables which have relationship with
eachother, however, when bind a certain datatable in the dataset to a
Gridview, you found the gridview only display one dimension data only (with
out the related parent table's values) and you're wondering how to make the
GridView display the related table's data(through the foreign key column),
correct? If there is anything I missed or didn't quite address, please feel
free to let me know.

Based on my understanding, the behavior yet is expected due to the ASP.NET
webform page's databinding mechanism. ASP.NET template control databinding
is quite different from winform control databinding. In winform, since the
datasoure is always in memory, the databound context is easy to track the
datasource and navigate between the current bound datatable to its related
parent or child table. However, in ASP.NET since the page must be flushed
and write out to clent, it can not hold the datasource in memory forever,
it just query the current attached datasource(tabl e or view) and bind that
direct attached table/view's data/columns to the databound
control(Gridvie w, datagrid ....). that's why you'll find GridView directly
display the foreign key value rather than the detailed value in
parent/child table/view.

To resolve this in webform page, we need to manually customize the
databinding process. for example, we can use the databound control such as
GridView's Item/Row DataBound event to do the customization.
#GridView.RowDa taBound Event
http://msdn2.microsoft.com/en-us/lib...trols.gridview.
rowdatabound.as px

In the RowDataBound event, we can access the current GridView Row's inner
sub controls(in each gridviewRow column). Also, we can access the current
databound data item(such as DataRowview). Then, we can manualy get the
related data (parent or sub rows through the DAtaRowView) and use it to
modify the certain Gridview row column's controls. for example:
the following Gridview is bound to a DataView(from a datatable which
contains the Northwind "products" table's data), and the container dataset
also contains another datatable ("categories " table in northwind), I add a
relation between them and bind the products view to the GridView. In the
RowDataBound event, I manually query parent row data from Categories table:
=====aspx template======= ===

<asp:GridView ID="GridView1" runat="server" AutoGenerateCol umns="False"
OnRowDataBound= "GridView1_RowD ataBound">
<Columns>
<asp:BoundFie ld DataField="Prod uctID"
HeaderText="Pro ductID" />
<asp:BoundFie ld DataField="Prod uctName"
HeaderText="Pro ductName" />
<asp:TemplateFi eld HeaderText="Cat egory">
<EditItemTempla te>
<asp:TextBox ID="txtCategory " runat="server"
Text='<%# Bind("CategoryI D") %>'></asp:TextBox>
</EditItemTemplat e>
<ItemTemplate >
<asp:Label ID="lblCategory " runat="server"
Text='<%# Bind("CategoryI D") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateFie ld>
</Columns>
</asp:GridView>

==============c ode behind========= =====

protected void Page_Load(objec t sender, EventArgs e)
{
if (!IsPostBack)
{
PerformDataBind ();
}
}

protected void PerformDataBind ()
{
//get the dataset which contains two datatables that have relation
DataSet ds = GetDataSet();

ds.Relations.Ad d("products_cat egories",
ds.Tables[1].Columns["CategoryID "], ds.Tables[0].Columns["CategoryID "]);
GridView1.DataS ource = ds.Tables[0].DefaultView;

GridView1.DataB ind();
}
protected void GridView1_RowDa taBound(object sender, GridViewRowEven tArgs e)
{
if (e.Row.RowType == DataControlRowT ype.DataRow)
{
DataRowView product = e.Row.DataItem as DataRowView;

string strCategory =
product.Row.Get ParentRow("prod ucts_categories ")["CategoryNa me"] as string;

Label lbl = e.Row.FindContr ol("lblCategory ") as Label;

lbl.Text = strCategory;
}
}

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

Hope this helps. If you have anything unclear on this, please feel free to
post here.

Regards,

Steven Cheng
Microsoft Online Community Support
=============== =============== =============== =====

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Jun 9 '06 #3
BTW, google doesn't help you out with these posts if you are an MSDN
subscriber, since you have to have a "real" email address. This one is from
MSDN.

Bill

"Steven Cheng[MSFT]" wrote:
Hello Bill,

Welcome to the ASPNET newsgroup.

From your description, you're building a data display page in ASP.NET
application(2.0 ). Currently you have
a Dataset that contains multiple datatables which have relationship with
eachother, however, when bind a certain datatable in the dataset to a
Gridview, you found the gridview only display one dimension data only (with
out the related parent table's values) and you're wondering how to make the
GridView display the related table's data(through the foreign key column),
correct? If there is anything I missed or didn't quite address, please feel
free to let me know.

Based on my understanding, the behavior yet is expected due to the ASP.NET
webform page's databinding mechanism. ASP.NET template control databinding
is quite different from winform control databinding. In winform, since the
datasoure is always in memory, the databound context is easy to track the
datasource and navigate between the current bound datatable to its related
parent or child table. However, in ASP.NET since the page must be flushed
and write out to clent, it can not hold the datasource in memory forever,
it just query the current attached datasource(tabl e or view) and bind that
direct attached table/view's data/columns to the databound
control(Gridvie w, datagrid ....). that's why you'll find GridView directly
display the foreign key value rather than the detailed value in
parent/child table/view.

To resolve this in webform page, we need to manually customize the
databinding process. for example, we can use the databound control such as
GridView's Item/Row DataBound event to do the customization.
#GridView.RowDa taBound Event
http://msdn2.microsoft.com/en-us/lib...trols.gridview.
rowdatabound.as px

In the RowDataBound event, we can access the current GridView Row's inner
sub controls(in each gridviewRow column). Also, we can access the current
databound data item(such as DataRowview). Then, we can manualy get the
related data (parent or sub rows through the DAtaRowView) and use it to
modify the certain Gridview row column's controls. for example:
the following Gridview is bound to a DataView(from a datatable which
contains the Northwind "products" table's data), and the container dataset
also contains another datatable ("categories " table in northwind), I add a
relation between them and bind the products view to the GridView. In the
RowDataBound event, I manually query parent row data from Categories table:
=====aspx template======= ===

<asp:GridView ID="GridView1" runat="server" AutoGenerateCol umns="False"
OnRowDataBound= "GridView1_RowD ataBound">
<Columns>
<asp:BoundFie ld DataField="Prod uctID"
HeaderText="Pro ductID" />
<asp:BoundFie ld DataField="Prod uctName"
HeaderText="Pro ductName" />
<asp:TemplateFi eld HeaderText="Cat egory">
<EditItemTempla te>
<asp:TextBox ID="txtCategory " runat="server"
Text='<%# Bind("CategoryI D") %>'></asp:TextBox>
</EditItemTemplat e>
<ItemTemplate >
<asp:Label ID="lblCategory " runat="server"
Text='<%# Bind("CategoryI D") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateFie ld>
</Columns>
</asp:GridView>

==============c ode behind========= =====

protected void Page_Load(objec t sender, EventArgs e)
{
if (!IsPostBack)
{
PerformDataBind ();
}
}

protected void PerformDataBind ()
{
//get the dataset which contains two datatables that have relation
DataSet ds = GetDataSet();

ds.Relations.Ad d("products_cat egories",
ds.Tables[1].Columns["CategoryID "], ds.Tables[0].Columns["CategoryID "]);
GridView1.DataS ource = ds.Tables[0].DefaultView;

GridView1.DataB ind();
}
protected void GridView1_RowDa taBound(object sender, GridViewRowEven tArgs e)
{
if (e.Row.RowType == DataControlRowT ype.DataRow)
{
DataRowView product = e.Row.DataItem as DataRowView;

string strCategory =
product.Row.Get ParentRow("prod ucts_categories ")["CategoryNa me"] as string;

Label lbl = e.Row.FindContr ol("lblCategory ") as Label;

lbl.Text = strCategory;
}
}

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

Hope this helps. If you have anything unclear on this, please feel free to
post here.

Regards,

Steven Cheng
Microsoft Online Community Support
=============== =============== =============== =====

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Jun 9 '06 #4
Thanks for your response Bill,

=============== ============
I guess the alternative to achieving the
same functionality is to use stored procedures for the CRUD interface
but ... you lose the caching from the dataset, Correct?
=============== ===========
Agree, actually I had ever thought about suggest you do the table join at
database layer(through T-SQL in stored procedure ...), but I gave it up
since I assume that you're looking for a application layer approach(in .net
code) :-).
Anyway, I think use T-SQL join will have better performance for the data
generation, and about the cache you mentioned, if the whole data is not
changable, we can still cache the returned result set(if you load it into a
DataSet/DataTable) in our application cache.

BTW, how about creating a View for this particular resultset, then, at
appliaction layer(ADO.NET), we just treat it as a normal DataTable. Anyway,
you can post this in DataBase specific groups for better ideas in database
layer.
=============== ===============
Are there any other options? The one I outlined below is interesting,
but it seems you are getting the same data twice. If I could some how
Fill()'s for the two related tables (two fills thru two table
adapters), then build a third table from the cached tables to satisfy
the relation .... Am I insane or is there something missing from the
FW?
=============== ===============

Sorry but I'm not very clear on this you mentioned, would provide some
further description. As far I know, as for single DataAdapter, you can fill
muliple datatables (into a dataset) through one "Fill" call. You can
specify a multiple-select query statement for the DataAdapter, e.g.

=============== =====
protected void Page_Load(objec t sender, EventArgs e)
{

string strSql = "select CategoryID, CategoryName from
Categories;sele ct ProductID, ProductName, CategoryID from Products";
SqlConnection conn = new
SqlConnection(W ebConfiguration Manager.Connect ionStrings["LocalNorthwind ConnS
tr"].ConnectionStri ng);
SqlDataAdapter adapter = new SqlDataAdapter( strSql, conn);

DataSet ds = new DataSet();

adapter.Fill(ds );

Response.Write( "<br/>Table Count: " + ds.Tables.Count );
}
=============== ==========

After you got the DataTable at .net layer, you should determine how to
cache those tables. It is hard to provide a common strategy since that
mostly depend on your data's relationship and how will they be used in the
application(how frequent, how changable?)...

Hope this also helps some.

Regards,

Steven Cheng
Microsoft Online Community Support
=============== =============== =============== =====

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Jun 12 '06 #5
Hey Bill,

Have you got any further ideas or progress on this issue? If there is still
anything we can help, please don't hesitate to post here.

Regards,

Steven Cheng
Microsoft MSDN Online Support Lead
=============== =============== =============== =====

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Jun 14 '06 #6

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

Similar topics

2
4884
by: Jordan O'Hare | last post by:
Hello Everyone, I am after some help with the following: I have a windows application that contains a list box and two data grids. All three controls are binded to a dataset that contains five tables, and three relations that I want to take advantage of. Everything works fine however I want to use the data grid table style editor to make it look more presentable. Currently I have successfully done this
1
1577
by: Iain | last post by:
I've a fairly complex schema which I'm trying to create a typed data set for. I've had a number of issues to date but it is sort of working (e.g. elements are not considered nullable unless minOccurs="0" is present. If not the codegen:nullValue attribute is ignored). What I'm seeing at the moment is that if I do NOT add in key and key ref relations, the cs generated puts in sensibly named relations with appropriate accessors. But...
0
1190
by: Joe Van Meer | last post by:
Hi all, I have a question regarding data relations within a data set. Say I have 3 tables named CLIENT, BOOKING and EMPLOYEE and I wanted to relate the first two tables (CLIENT AND BOOKING) via a clientid and relate the second set of tables (BOOKING AND EMPLOYEE) using an employeeid. My problem arises when there a re no records in one of the tables in either data relation. What is the best way to handle this, check the number of...
17
3040
by: Justin Emlay | last post by:
I'm hopping someone can help me out on a payroll project I need to implement. To start we are dealing with payroll periods. So we are dealing with an exact 10 days (Monday - Friday, 2 weeks). I have a dataset as follows (1 week to keep it short): Employee 1 - Date 1 Employee 1 - Date 2
7
14826
by: | last post by:
Hello, Does anyone have an idea on how I can filter the data in the gridview control that was returned by an sql query? I have a gridview that works fine when I populate it with data. Now I want to look at that data and filter it based on what is in it. I know that this could have been done with data sets and data views in asp.net 1.1 but how is this done now in asp.net 2.0?
3
1760
by: topmind | last post by:
I am generally new to dot.net, coming from "scriptish" web languages such as ColdFusion and Php. I have a few questions if you don't mind. First, how does one go about inserting dynamic SQL during run-time without lots of quotes? For example, adding "AND" clauses that may or may not be present based on the query criteria form. Some of the asp.net examples use the one-line append approach which
1
2985
by: MattC | last post by:
Hi, Given an ObjectDataSource and GridView declared as: <asp:ObjectDataSource runat="server" ID="FullCategoryList" TypeName="AD.App_Code.CategoryDataMapper" SelectMethod="GetCategories" SortParameterName="SortExpression" DataObjectTypeName="AD.App_Code.Category" UpdateMethod="UpdateCategory"></asp:ObjectDataSource>
9
11940
by: lilOlMe | last post by:
Hi there! I have generated a GridView that looks something like: SportName| CompanyNameX |CompanyNameY |CompanyNameZ Hockey.....| Shipping------------ |Accounting-------- |Shipping------------ BaseBall...| Receiving-----------|Shipping------------|Accounting--------- Etc............| Accounting----------|Receiving---------- |Receiving----------- Where there are an unknown number of Company Names and an unknown number of Sport...
0
3628
by: dhyder | last post by:
I'm working on an admin page for a SQL Server 05 db. The page is in ASP.NET 2.0/C#. The db has multiple tables with foreign keys/constraints. I have multiple SqlDataSources and GridViews, which are doing the select/update/delete methods. I manually did the Insert method for each Gridview and I am able perform error handling on it. Textboxes for data to add <asp:Button ID="btnInsertNewService runat="server" Text="Submit"...
0
9901
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
9750
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
10672
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10744
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
10364
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
7077
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
5937
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4550
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3182
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.