Handling data relations in Gridview

S

sutphinwb

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
 
S

Steven Cheng[MSFT]

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(table or view) and bind that
direct attached table/view's data/columns to the databound
control(Gridview, 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.RowDataBound Event
http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.
rowdatabound.aspx

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" AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" />
<asp:BoundField DataField="ProductName"
HeaderText="ProductName" />
<asp:TemplateField HeaderText="Category">
<EditItemTemplate>
<asp:TextBox ID="txtCategory" runat="server"
Text='<%# Bind("CategoryID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"
Text='<%# Bind("CategoryID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

==============code behind==============

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

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

ds.Relations.Add("products_categories",
ds.Tables[1].Columns["CategoryID"], ds.Tables[0].Columns["CategoryID"]);


GridView1.DataSource = ds.Tables[0].DefaultView;

GridView1.DataBind();
}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView product = e.Row.DataItem as DataRowView;

string strCategory =
product.Row.GetParentRow("products_categories")["CategoryName"] as string;

Label lbl = e.Row.FindControl("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.)
 
S

sutphinwb

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
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(table or view) and bind that
direct attached table/view's data/columns to the databound
control(Gridview, 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.RowDataBound Event
http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.
rowdatabound.aspx

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" AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" />
<asp:BoundField DataField="ProductName"
HeaderText="ProductName" />
<asp:TemplateField HeaderText="Category">
<EditItemTemplate>
<asp:TextBox ID="txtCategory" runat="server"
Text='<%# Bind("CategoryID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"
Text='<%# Bind("CategoryID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

==============code behind==============

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

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

ds.Relations.Add("products_categories",
ds.Tables[1].Columns["CategoryID"], ds.Tables[0].Columns["CategoryID"]);


GridView1.DataSource = ds.Tables[0].DefaultView;

GridView1.DataBind();
}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView product = e.Row.DataItem as DataRowView;

string strCategory =
product.Row.GetParentRow("products_categories")["CategoryName"] as string;

Label lbl = e.Row.FindControl("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.)
 
G

Guest

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 said:
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(table or view) and bind that
direct attached table/view's data/columns to the databound
control(Gridview, 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.RowDataBound Event
http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.
rowdatabound.aspx

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" AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" />
<asp:BoundField DataField="ProductName"
HeaderText="ProductName" />
<asp:TemplateField HeaderText="Category">
<EditItemTemplate>
<asp:TextBox ID="txtCategory" runat="server"
Text='<%# Bind("CategoryID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"
Text='<%# Bind("CategoryID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

==============code behind==============

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

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

ds.Relations.Add("products_categories",
ds.Tables[1].Columns["CategoryID"], ds.Tables[0].Columns["CategoryID"]);


GridView1.DataSource = ds.Tables[0].DefaultView;

GridView1.DataBind();
}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView product = e.Row.DataItem as DataRowView;

string strCategory =
product.Row.GetParentRow("products_categories")["CategoryName"] as string;

Label lbl = e.Row.FindControl("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.)
 
S

Steven Cheng[MSFT]

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(object sender, EventArgs e)
{

string strSql = "select CategoryID, CategoryName from
Categories;select ProductID, ProductName, CategoryID from Products";
SqlConnection conn = new
SqlConnection(WebConfigurationManager.ConnectionStrings["LocalNorthwindConnS
tr"].ConnectionString);
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.)
 
S

Steven Cheng[MSFT]

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.)
 
Joined
May 11, 2006
Messages
2
Reaction score
0
I think that the best solution is writing something like:

Code:
<asp:Label
	ID="lblText"
	runat="server"
	Text='<%# DataBinder.Eval(((DataRowView)Container.DataItem).Row, "ParentRow.ItemName") %>'
/>

This is valid for the case of typed datasets, when the row contains the property 'ParentRow' which in turn contains the property 'ItemName'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top