在Web窗体ASP.NET应用程序中,我有一个存储过程,它连接两个表,如下所示:
CREATE PROCEDURE dbo.usp_DepartmentsServiceChannelsSelect
AS
SET NOCOUNT ON
SELECT d.ID, d.Description, s.ServiceChannel
FROM Departments d
INNER JOIN [ServiceChannels] s
ON s.ID = d.ServiceChannel
GO
因此,部门会被选中,ID,描述和连接到部门的ServiceChannel也会被返回。
我在类型化数据集中使用此存储过程,其中TableAdapter
名为Department
,其方法为GetDepartmentsWithServiceChannels
:
static public DepartmentDataTable GetDepartmentsWithServiceChannels()
{
using (DepartmentTableAdapter departmentTA = new DepartmentTableAdapter())
{
return departmentTA.GetDepartmentsWithServiceChannels();
}
}
我在视图中使用此方法在代码隐藏中绑定DepartmentCollection
,如下所示:
private void BindDepartmentsAfterSorting(string sortexpression, SortDirection
sortDirection)
{
DepartmentCollection deptCollection =
ServiceInterfaceRegistry.DepartmentManager.GetDepartments(false);
if (deptCollection != null)
{
Common.Comparer<Department> objcmp = new Common.Comparer<Department>();
objcmp.SortClasses.Add(new SortClass(sortexpression, sortDirection));
deptCollection.Sort(objcmp);
}
MyGridView.DataSource = deptCollection;
MyGridView.DataBind();
}
MyGridvIew
如下所示:
<asp:GridView ID="MyGridView" runat="server" DataKeyNames="ID" AutoGenerateColumns="False" Width="1000px"
AllowSorting="True" AllowPaging="True" EmptyDataText="Geen afdeling gevonden." OnRowDataBound="AfdelingGridView_RowDataBound" OnRowDeleting="AfdelingGridView_RowDeleting" OnRowEditing="MyGridView_RowEditing" OnPageIndexChanging="AfdelingGridView_PageIndexChanging" OnSorting="AfdelingGridView_Sorting">
<Columns>
<asp:ButtonField ButtonType="Button" Text="Delete/edit" CommandName="Edit">
<ItemStyle Width="20px" />
</asp:ButtonField>
<asp:TemplateField Visible ="False">
<ItemTemplate>
<asp:Button ID="Delete" runat="server" CommandName="Delete"
Text="Verwijderen" Font-Bold="false" />
</ItemTemplate>
<ItemStyle Width="20px" />
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Description" ReadOnly="True" SortExpression="Description" />
<asp:BoundField DataField="ServiceChannel" HeaderText="Service Channel" ReadOnly="True" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
</asp:GridView>
不幸的是,return departmentTA.GetDepartmentsWithServiceChannels()
部分会返回以下错误:
输入字符串的格式不正确。无法存储 在ServiceChannel列中。预期的类型是Int32。
如何让GridView
显示外键的字符串值?
答案 0 :(得分:0)
解决方案是使ServiceChannel
对象具有基于数据表的ID属性,并在GetDepartments
方法中匹配此对象的ID:
Department tmpDepartment = new Department(departmentRow);
tmpDepartment.ServiceChannel = channels.Where(c => c.Id ==
departmentRow.ServiceChannelID).FirstOrDefault();
然后可以通过
在视图上访问此属性e.Row.Cells[e.Row.Cells.Count - 1].Text = ((Department)
e.Row.DataItem).ServiceChannel.Description;