ASP 4.5 GridView Template Field with possible null object - asp.net

I have a list of objects in my GridView where the child object could be null. I can't seem to get the right syntax to test for null and ignore/print empty string.
I see 3 possible answers for this:
This can be done easily in the aspx file in a declarative way
I have to do it in code behind
it can't be done like this and I need to sort out my list method and project a new one with no nulls, something like that.
Here is the grid view code, GetMyData is a method that just returns IEnumerable<MyClass> and this comes from EntityFramework where I'm using the Include method to eager load the Customer object.
<asp:GridView runat="server"
CssClass="listTable"
ItemType="MyClass"
DataKeyNames="ID"
SelectMethod="GetMyData"
AutoGenerateColumns="false"
AlternatingRowStyle-CssClass="listAlternate">
<Columns>
<asp:DynamicField DataField="ReferenceDate" />
<asp:TemplateField>
<ItemTemplate>
<%# (Item.Customer != null) ? Item.Customer .Name : ""; %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please note, I'm using entity framework 6.1 and .Net 4.5 in this project

Don't use ;
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Item.Customer") != null ? Eval("Item.Customer.Name) : "" %>
</ItemTemplate>
</asp:TemplateField>

Related

Gridview Hyperlinkfield using DataNavigateUrlFormatString with Ampersand

So I have gridview pulling fields from a table and my hyperlinkfield is used to go to a specific page for that row to get more detailed data. Everything seems to work great except when the field used in the hyperlinkfield has an ampersand. I assume it is reading the ampersand as something else and so it doesn't bring up the proper info because the ampersand is in the name in the database.
Hyperlinkfieldcode:
<asp:HyperLinkField HeaderText="Name" Text="{0}" DataNavigateUrlFields="Name" DataNavigateUrlFormatString="item.aspx?name={0}" DataTextField="Name" />
Example:
A clicking on the name "test item" would take you to mysite.com/item.aspx?name=test%20item and this works.
However, clicking on "test & test item" it takes you to mysite.com/item.aspx?name=test%20item%20&%20item which does not work. It just pulls up a page with blank info.
What can I do to fix this?
Update:
I converted the hyperlinkfield to a hyperlink inside a template field, but the url is now coming out weird.the url now comes out like mysite.com/item.aspx?name=System.Int32%5b%5d
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink runat="server" Text='<%#Eval("Name") %>' DataNavigateUrlFields="Name" NavigateUrl='<%# "name.aspx?name=" + HttpUtility.UrlEncode({0}.ToString())%>' DataTextField="Name" />
</ItemTemplate>
</asp:TemplateField>
My original answer was incomplete (due to not being able to see the entire code). This answer will contain the missing elements.
The main object is to UrlEncode the data field Name, so that it can be used as (part of) a url link .
1 - First we must ensure that the field "Name", is listed as DataKeyNames for the GridView as follows:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name" ...
2 - Secondly (if using a navigateURL) create a TemplateField i.e. (asp:TemplateField ) and use Eval() method to access the DataField in conjunction with UrlEncode() .
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="NameLink" runat="server" Text='<%# Eval("Name") %>' NavigateUrl='<%# "name.aspx?name=" + HttpUtility.UrlEncode(Eval("Name").ToString())%>' ></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Option 2 Alternatively you can use a HyperLinkField and DataNavigateURL but you should still designate Name as a DataKeyNames .
Hope this works with no problems. Let me know if any clarification is needed.
Happy coding and Cheers,

error message "String was not recognized as a valid Boolean" in aspx page

I have a SQL stored proc where I am creating a column ("Certified") dynamically based on two other columns. The value from this column is a '0' or '1'. The SQL stored proc query is:
, CASE WHEN
(StartMiles < EndMiles)
AND (StartTime < EndTime)
AND (bcd.Status != 'C')
THEN '1' ELSE '0' END
AS Certified
On the front end in my aspx page, I have a telerik radgrid that will display a checkbox (enabled if value is 1, disabled if value is 0). The aspx code is:
<telerik:GridTemplateColumn DataField="Certified" HeaderText="Certified" Visible="true">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox2_CheckedChanged"
Enabled='<%# !bool.Parse(Eval("Certified").ToString()) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
I am getting an error on the aspx page String was not recognized as a valid Boolean
To resolve the error, how can I set a datatype in the stored proc?
<telerik:GridTemplateColumn DataField="Certified" HeaderText="Certified" Visible="true">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox2_CheckedChanged"
Enabled='<%# !Convert.ToBoolean(Convert.ToInt32(Eval("Certified").ToString())) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
I would recommend using a code-behind method to do this instead of putting logic into the markup via embedded code blocks, like this:
Markup:
<telerik:GridTemplateColumn DataField="Certified" HeaderText="Certified"
Visible="true">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox2_CheckedChanged"
Enabled='<%# IsCertified(Eval("Certified").ToString()) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
Code-behind:
protected bool IsCertified(string certifiedValue)
{
return !bool.Parse(certifiedValue);
}
Note: To be safer, I would recommend using the Boolean.TryParse() method instead of just the Parse(), as that will eliminate the chance of a string that cannot be parsed into a bool from throwing an exception. Read Boolean.TryParse Method documentation for more information.
This provides two advantages, in my opinion, over the OP code:
Simplified markup, because you do not have conditional logic in the markup, but now just a call to the method.
You can leverage the power of Visual Studio's IntelliSense, compiler to catch syntax errors at compile-time instead of run-time and the debugger itself.

Get the this object using eval in a gridview in asp

I can't find any answer anywhere. I want to refer to the row object itself in an databinding expression in a gridview, like this:
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label runat="server"
Text = '<%# GetPendingReason(Eval("this")) %>' />
</ItemTemplate>
</asp:TemplateField>
But it doesn't work because "this" doesn't refer to any attribute. Referencing individual attributes works fine, but how do you refer to the current row?
Simply use <%# Container.DataItem %>. Do not use Databinder.
If you want to refer to the current row you do that at codebehind using
GridViewRow row = GridView1.Rows[index];
at any of the GridView event.

Databinding exception with entity navigation property

I have two Entity classes: Order and OrderItem. Order contains a navigation property OrderItemSet of type
System.Data.Objects.DataClasses.EntityCollection<OrderItem>
On an aspx page is a FormView bound to this EntityDataSource:
<asp:EntityDataSource ID="EntityDataSourceOrder" runat="server"
ConnectionString="name=EntitiesContext"
DefaultContainerName="EntitiesContext"
EntitySetName="Order"
Include="OrderItemSet"
// stuff to define a query
</asp:EntityDataSource>
The FormView is bound to the DataSource and the ItemTemplate of this FormView contains a ListView which I try to bind to the OrderItemSet. It looks this way:
<asp:FormView ID="FormViewOrder" runat="server" DataKeyNames="OrderID"
DataSourceID="EntityDataSourceOrder" AllowPaging="True" >
<ItemTemplate>
...
<asp:ListView ID="ListViewOrderItems" runat="server"
DataSource='<%# Eval("OrderItemSet")%>' >
...
</asp:ListView>
</ItemTemplate>
</asp:FormView>
When I run the application I get an exception pointing to the line DataSource='<%# Eval("OrderItemSet")%>' in markup and telling me:
DataBinding: System.Web.UI.WebControls.EntityDataSourceWrapper does not contain a property with name 'OrderItemSet'
What is wrong here?
(I've done the same with other navigation properties which are not lists but single object references, and that works.)
Thank you for help!
It seems to me that you are trying to evaluate a collection from within a datasource, without first binding to that datasource.
Why don't you try binding directly to the datasource? E.g.
<asp:ListView ID="ListViewOrderItems" runat="server"
DataSourceID="EntityDataSourceOrder"
...
</asp:ListView>

How do I data bind a drop down list in a gridview from a database table using VB?

So in this gridview, there is a column for status and I want to have a drop down list with Pass, Pending, Fail appear when the edit button is clicked. These values are already in a table, so I need to somehow bind from this table to each ddl for every row.
Here is the column from the gridview. As you can see, I would like to just have a label showing when not in edit mode, and a ddl when the edit button is pressed
<asp:TemplateField HeaderText="During Production Status" SortExpression="DuringProductionStatus">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" datavaluefield="Name"
datatextfield="Name" DataSource="*What goes here?*"> />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text='I don't understand how to get this from the ddl' />
</ItemTemplate>
</asp:TemplateField>
For clarity's sake, my table is named Status, and the database is named DirectImport
There's a few steps to go through here - none of them are particularly difficult, but they can be a bit fiddly (IMHO). The good news is once you've got this working once, it gets easier to do it again!
I'm assuming you've got a <asp:*DataSource> control on your page - my preference is for an ObjectDataSource but I don't think it matters, I think a SqlDataSource works equally well. I've never tried doing this with GridView.DataSource = MyDataSet in code-behind, so I don't know whether that would work or not, but my assumption is that it wouldn't as you wouldn't get the proper two-way binding that you want. This data source feeds your grid with your main data. The key point here is that your database query must return both the Status text field and the Status id.
So your gridview will now look something like:
<asp:objectdatasource runat="server" id="MainDataSource" ... />
<asp:gridview runat="server" id="MyGridView" DataSourceID="MainDataSource">
<Columns>
<asp:TemplateField HeaderText="During Production Status" SortExpression="DuringProductionStatus">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text="<%# Bind('Status') %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
The Text="<%# Bind('Status') %>" is the bit you're missing to get the status text into the grid.
Now add a second data source into your markup that reads in the set of values from the Status table.
<asp:objectdatasource runat="server" id="StatusObjectDataSource" ... />
And add the EditItemTemplate into the GridView, which is bound to the Status DataSource.
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" datavaluefield="StatusID"
datatextfield="Status" DataSourceID="StatusObjectDataSource"
SelectedValue="<%# Bind('StatusId') %>" />
</EditItemTemplate>
The SelectedValue="<%# Bind('StatusId') %>" is what connects up the two datasets so that when you flip a row into Edit mode, the dropdownlist has the correct item already selected, and when you then save it you've got the Status ID to put into your database.
And you're done.
I have used the RowDataBound event. Here is a small code snippet. HTH
you would have an ItemTemplate in your aspx/ascx
<asp:TemplateField HeaderText="Column Headings">
<ItemTemplate>
<asp:DropDownList ID="ddlName" runat="server" Width="150"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
and in your code behind, you will have
protected void grdDataMap_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlName");
ddl.DataSource = someList;//the source of your dropdown
ddl.DataBind();
}
}
so when you bind your grid with grdDataMap.Databind (assuming your grid id is grdDataMap), row databound event will be called for each row (including header/footer, and thats the reason you check RowType)
so you can probably decide what controls/columns to hide/show/bind inside this row databound event
In the winforms world I pull my objects from the DB into a List(Of Whatever) and use the list as the datasource.
This also lets me add extra "convenience" fields in the object so that I can populate it with stuff from other tables.
I don't know asp.net at all so if you can do something similar, it might help.
A really quick solution is to create a custom web control for the status dropdown. The control will always contain the same data. When it renders you populate the datasource. When it gets added to the gridview, the data will be in the drop down. Hope that helps!

Resources