asp.net entity framework <%# Bind("linkedTable.Field") %> - c#

.NET 4 ASP.NET
I have a DetailsView that is displaying an entity framework record for a table that has a linked lookup table. I have an asp:BoundField with the datafield set as "linkedTable.Field" and it displays a value.
<asp:BoundField DataField="linkedTable.Field" HeaderText="linkedTable.Field"
SortExpression="linkedTable.Field" />
I am trying to use that value in an asp:TemplateField but when I try to get it using:
<asp:TemplateField HeaderText="Field" SortExpression="linkedTable.Field" >
<EditItemTemplate>
<asp:Label runat="server" ID="lblField" Text='<%# Bind("linkedTable.Field") %>' />
</EditItemTemplate>
</asp:TemplateField>
Nothing shows up in the label. I can change the Bind() to a field that is not part of the linked table and it works (i.e. the "ID" field). My problem is I don't understand why the linkedtable.Field value shows up in one context and not in the other.
FYI, my data connection is a EntityDataSource
<asp:EntityDataSource ID="edsNYSEDaily" runat="server"
ConnectionString="name=ServerDBEntities"
DefaultContainerName="ServerDBEntities" EntitySetName="tblNYSE"
EntityTypeFilter="tblNYSE" EnableUpdate="True" EnableFlattening="true"
AutoGenerateWhereClause="True" Select="" Where="">
<WhereParameters>
<asp:QueryStringParameter DefaultValue="0" Name="ID"
QueryStringField="ID" Type="Int32" />
</WhereParameters>
Let me know if you need any other information. I am stuck

Ok, discovered the problem:
Needed to add Include="linkedTable" to the EntityDataSource tag. Still not sure why it was even working in the <asp:DataBound /> tag.
Source for the answer: forums.asp.net
Copy of the text:
you should start here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.include.aspx
notice that, you won't be able to Bind (I mean two-way data-binding) the related entities (see the remarks there).
and, you'd have to use a TemplateField for those properties.
see this example (I used the link table 'TableAB' for EntitySetName and included the other two):
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="EntityDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="IDA" HeaderText="IDA" SortExpression="IDA" />
<asp:BoundField DataField="IDB" HeaderText="IDB" SortExpression="IDB" />
<asp:TemplateField HeaderText="TableA Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TableA.NameA") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TableB Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("TableB.NameB") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=ABLinkEntities"
DefaultContainerName="ABLinkEntities" EnableDelete="True" EnableFlattening="False"
EnableInsert="True" EnableUpdate="True" EntitySetName="TableABs" Include="TableA,TableB">
</asp:EntityDataSource>
you'll have to re-consider the updates and deletes, you could do them manually.

Related

Display multiple glyphicon's in gridview column based on flags

I have a gridview with bounded fields. In the first column "Priority" I'd like to bind the priority number but also add multiple glyphicon's based on flags from other columns in the datatable. There are columns "HOT_FLAG", "WATCH_FLAG" and "INFO_FLAG" and if those are true, I need to display the corresponding glyphicon.
<asp:GridView
ID="dgv_Test"
GridLines="None"
AutoGenerateColumns="False"
OnRowCreated="dgv_RowCreated"
EnableHeadervisualstyles ="true"
runat="server">
<Columns>
<asp:BoundField DataField="PRIORITY" HeaderText="#"/>
<asp:BoundField DataField="COL2" HeaderText="COL2" />
<asp:BoundField DataField="COL3" HeaderText="COL3" />
</Columns>
</asp:GridView>
I'm assuming I need to convert these bound fields to template fields (or something else) and set the Glyphicon's in the code behind but I'm not sure where to go from here.
Try this.
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<asp:Image ID="HotFlag" runat="server" ImageUrl="path/to/image" Visible='<%# Eval("HOT_FLAG") %>'/>
<asp:Image ID="WatchFlag" runat="server" ImageUrl="path/to/image" Visible='<%# Eval("WATCH_FLAG") %>'/>
<asp:Image ID="InfoFlag" runat="server" ImageUrl="path/to/image" Visible='<%# Eval("INFO_FLAG") %>' />
</ItemTemplate>
</asp:TemplateField>

ASP.NET SqlDataSource filter behaviour

I have a GridView object fed trough a SqlDataSource. In the same form I have also a number of TextBoxes used to build a filtering expression for the datasource. The filtering is started by pressing a Button.
<asp:GridView
DataSourceID="sdsTable1"
OnSorting="gvTable1_Sorting"
OnPageIndexChanging="gvTable1_PageIndexChanging"
runat="server"
CssClass="list_table"
ID="_gvTable1"
CellPadding="0" CellSpacing="0"
AutoGenerateColumns="false"
EmptyDataText="No data."
ShowHeader="true" ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
OnRowDataBound="gvTable1_RowDataBound" >
<HeaderStyle CssClass="header" />
<FooterStyle CssClass="footer" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Next page"
PreviousPageText="Prev page"
FirstPageText="First page"
LastPageText="Last page" />
<RowStyle CssClass="odd" />
<AlternatingRowStyle CssClass="even" />
<PagerStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="date">
<ItemTemplate>
<%#Eval("date","{0:dd/MM/yyyy HH:mm:ss}")%>
</ItemTemplate>
<FooterTemplate>
TOTALE:
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("price","{0:F2} €") %>'>></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsTable1" runat="server"
ConnectionString="<%$ ConnectionStrings:_db %>"
ProviderName="<%$ ConnectionStrings:_db.ProviderName %>"
DataSourceMode="DataSet"
SelectCommand=" SELECT id, id_user, price, description FROM view1 WHERE id_user = #id_user;">
<SelectParameters>
<asp:SessionParameter Type="Int32" Name="id_user" SessionField="USER_ID" />
</SelectParameters>
</asp:SqlDataSource>
In codebehind (in the event hanlder associated with the Button mentioned above) I build up the filter expression chaining TextBoxes values, with this code:
if (!string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()))
{
_sFilter += "(description LIKE '%" + _txtFilter0.Text.Trim() + "%')";
}
if (!string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()))
{
if (!string.IsNullOrWhiteSpace(_sFilter))
_sFilter += " AND";
_sFilter += "(description LIKE '%" + _txtFilter1.Text.Trim() + "%')";
}
sdsTable1.FilterExpression = _sFilter;
Everything works until I clear the fields that leads to an empty filter, im such circumstances I expected to retrieve all the records but for some reason, in this case, the last recordset is kept and shown apparently without a reason.
I tried also to disable the SQLDataSource caching feature without luck:
EnableCaching="false"
I tried also to issue a Select command, again without luck:
sdsTable1.Select(DataSourceSelectArguments.Empty);
Where I'm wrong?
Your _sFilter property will be persisted across postbacks, so as you're only updating it when your filter text boxes are not empty it will remain at the last set value when you clear them. Putting a breakpoint in your code at the line _sdsTable1.FilterExpression = _sFilter; should confirm this.
To solve the issue, either clear the _sFilter property before rebuilding it in your event handler, or write an additional check:
if (string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()) & string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()) )
{
_sFilter = null;
}

ASP.NET: Download file from database when clicking on file name on Grid View

I have a grid view that displays all of uploaded files of an employee (data from SQL DB).
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="true" ShowFooter="false" PageSize="5"
CssClass="table" AlternatingRowStyle-BackColor="WhiteSmoke"
HeaderStyle-BackColor="#6C7A95" HeaderStyle-BorderColor="#666666" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="2" HeaderStyle-ForeColor="White"
OnPageIndexChanging="OnPaging" EmptyDataText="No Documents">
<Columns>
<asp:BoundField DataField="file_name" HeaderText="File Name" />
<asp:BoundField DataField="upload_date" HeaderText="Date (GMT -7)" />
<asp:BoundField DataField="file_status" HeaderText="Status" />
<asp:TemplateField HeaderText="Employee's Note">
<ItemTemplate>
<a data-original-title='<%# Eval("emp_note")%>' href="#" class="demo-cancel-click" rel="tooltip"><i class="icon-book"></i></a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The interface look like this:
I like to archive this: the file name will be a link button (or whatever the best way is) and when click on name it will download the file. So I modified the File Name column:
<asp:TemplateField HeaderText =" File Name">
<asp:ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server"
OnClick="DownloadFile" Text='<%#Eval("file_name") %>'
CommandArgument='<%# Eval("file_id") %>'></asp:LinkButton>
</asp:ItemTemplate>
</asp:TemplateField>
But then the interface became: (file_name disappeared)
How do I get what I need?
You need to remove asp: from ItemTemplate. Your markup should look like below:
<asp:TemplateField HeaderText=" File Name">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server"
OnClick="DownloadFile" Text='<%#Eval("file_name") %>'
CommandArgument='<%# Eval("file_id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Hope it helps!

Paging not working in GridView when ajax control is removed

I have a grid view in my aspx page. I have enabled paging also.
Paging is working fine when an ajax control is in page, but when I removed the ajax control paging is not working anymore. ie, on clicking page number 2 grid becomes empty.
What could be the possible reason? Please suggest a solution.
code
<asp:GridView ID="SitesGrid" runat="server" AllowPaging="True" AllowSorting="True" DataSourceID="SitesDataMgr" AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="3" CellSpacing="3" OnRowDataBound="viewSite_RowDataBound" class="tbl_blck gridtable clearfix" PageSize="4" EmptyDataText="No rows found">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="clientID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-ForeColor="White" SortExpression="ClientName">
<ItemTemplate>
<asp:Label ID="clientLabel" runat="server" Text='<%# Bind("ClientName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" HeaderStyle-ForeColor="White" SortExpression="SiteStatus">
<ItemTemplate>
<asp:Label ID="siteLabel" runat="server" Text='<%# Bind("SiteStatus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details" HeaderStyle-ForeColor="White" >
<ItemTemplate>
<asp:LinkButton ID="viewSite" runat="server" OnClick="viewSite_click" CausesValidation="False" CommandName="Edit"
Text="View"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="SitesDataMgr" runat="server" ConvertNullToDBNull="True" OldValuesParameterFormatString="{0}" SelectMethod="GetAllSitesByUser" FilterExpression="ClientName LIKE '%{0}%'" TypeName="Creation.DataMgr">
<SelectParameters>
<asp:SessionParameter Name="createdUserID" Type="String" SessionField="strUserName" />
</SelectParameters>
<FilterParameters>
<asp:ControlParameter Name="ClientName" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:ObjectDataSource>
It looks like you have not added the SelectCount method to your ObjectDataSource.
This is required for the ObjectDatasource to correctly page your data.
Your select method needs the int parameters maximumRows and startRowIndex This is the default parameter names required for paging. if you do have them in. Please use them to filter your data.

How to define number of rows of GridView at runtime in code behind using C#

I need to develop such a program in which the GridView's rows should be decided at run time.
i.e. I have a table in database called dealer capacity.
Dealer_ID Capacity
D0001 5
Now when the Dealer D00001 is selected from combo box the number of rows in grid view should be 5. I want to use the template field also.
My code for GridView is:
<asp:GridView ID="grdlicence" runat="server" DataKeyNames="Version_id" GridLines="None" BorderStyle="Solid" AutoGenerateColumns="false" AllowSorting="true"
CssClass="mGrid table"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" >
<Columns>
<asp:BoundField DataField="Version_name" ItemStyle-CssClass="uppercase" ItemStyle-Width="150px" HeaderText="Version" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Version_id" Visible="false" HeaderText="Version" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<center><asp:TextBox ID="txtprice" CssClass="alignments TextStyle" MaxLength="5" runat="server" ></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Licence Id">
<ItemTemplate>
<center><asp:TextBox ID="txtlicenceid" CssClass="alignments uppercase" runat="server" ></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Purchase Date">
<ItemTemplate>
<center><asp:TextBox ID="txtpurchasedate" onfocus="showCalendarControl(this);" CssClass="alignments TextStyle" runat="server"></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry Date">
<ItemTemplate>
<center><asp:TextBox ID="txtexpirydate" onfocus="showCalendarControl(this);" CssClass="alignments TextStyle" runat="server"></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Upload File">
<ItemTemplate>
<center><asp:FileUpload ID="fileUpload" runat="server" /></center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to define PageSize for your GridView and remember to set AllowPaging to true for the GridView
GridView.PageSize Property
Gets or sets the number of records to display on a page in a GridView
control.
The default is 10.
You may see this article: GridView Paging Sample in ASP.NET
You can use the linq Take() and pass the number as parameter.
Updated according to the comment, use following code.
grdlicence.DataSourse= ds.Take(5);
grdlicence.DataBind();

Categories