Accessing asp.net controls of datalist in codebehind - c#

I am trying to access an asp Image tag in my code behind so that I can display a default image if there is no other image present. The problem that I am having is that I am getting an "Object reference not set to an instance of an object." error message.
The aspx page
<%# Control Language="C#" AutoEventWireup="true" CodeFile="MemberProfileList.ascx.cs"
Inherits="UserControls_MemberProfileList" %>
<%--<asp:GridView ID="GridView1" runat="server">
</asp:GridView>--%>
<asp:DataList ID="profilelist" runat="server" RepeatColumns="2" OnDataBinding="profilelist_DataBound" >
<ItemTemplate>
<asp:Image ID="ProfileImage" runat="server" ImageUrl='<%# System.String.Format("/Images/{0}", DataBinder.Eval(Container.DataItem, "ProfilePictureThumb"))%>' />
<asp:Hyperlink runat="server" NavigateUrl='<%#Link.ToSpecificMemberProfile(Eval("Username").ToString()) %>' Text='<%#HttpUtility.HtmlDecode(Eval("Username").ToString()) %>' />
</ItemTemplate>
</asp:DataList>
The method in the code behind
profilelist.DataSource = myProfileList;
profilelist.DataBind();
Image ProfileImage = profilelist.FindControl("ProfileImage") as Image;
string profilepic = ProfileImage.ImageUrl.ToString();
if (profilepic == null)
{
ProfileImage.Visible = false;
}
Any help is appreciated

The Image will be inside an Item, not on the whole List.
Implement your logic inside the ItemDataBound event.
Check this out: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx
Regards

//if you're trying to hide it base on weather the ProfilePictureThumb is Null by putting:**
<asp:Image ID="ProfileImage" Visible='<%# String.IsNullOrEmpty(Eval("ProfilePictureThumb").ToString())? false:true %>' runat="server" ImageUrl='<%# System.String.Format("/Images/{0}", DataBinder.Eval(Container.DataItem, "ProfilePictureThumb"))%>' />
//if you want to make it display a default image based on weather or not ProfilePicture is null:
ImageUrl='<%# String.IsNullOrEmpty(Eval("ProfilePictureThumb").ToString())? System.String.Format("/Images/{0}", "defaultimage.jpg"):System.String.Format("/Images/{0}", DataBinder.Eval(Container.DataItem, "ProfilePictureThumb"))%>'
//that way you don't need code behind.

Related

To get values from custom control

In the below code I have user controls like textbox, dropdown, checkbox, etc. and I bind it to a datalist. Now I have refer the controls to .aspx web page now my aim is to get the values of custom controls in .aspx page. Please help me to do this. My aim is to get the values of textbox, dropdown, checkbox from usercontrols in .aspx.
GmatField.ascx
<asp:TextBox ID="txtField" runat="server" width="200Px" CssClass="style22" ></asp:TextBox>
<asp:DropDownList ID="cbField" runat="server" width="200Px" >
</asp:DropDownList>
<asp:CheckBox ID="chField" runat="server" width="200Px" />
GmatField.ascx
<%# Register TagPrefix="gmat" TagName="FieldCont" Src="~/Search/GmatField.ascx" %>
<asp:DataList ID="dlFields" runat="server" Height="100px"
Width="50px" BorderColor="Beige">
<ItemTemplate>
<gmat:FieldCont ID="gmatFieldCont" runat="server" />
</ItemTemplate>
</asp:DataList>
NewDocument.aspx
<%# Register TagPrefix="gmat" TagName="GmatFieldsControl" Src="~/Search/GmatFields.ascx" %>
<gmat:GmatFieldsControl ID="gmatFieldsContr" runat="server" />
Simple.
Create a public property that gets the value from the textbox or selectedItem dropdownlist
Then from the page that implements that user control, you can then access the property:
// usercontrol:
public string TxtField
{
get
{
return this.txtField.Text;
}
}
// from the ASPX page that implements the usercontrol:
string txtFieldValue = this.gmatFieldsContr.TxtField;

How to find a control located inside datalist itemtemplate, on a Page_Load event?

I have a datalist which display's thumbnails of images and a download icon under it, when user clicks on the download icon, system download's the image at client's location.
<asp:DataList ID="dtlSearchDetails" runat="server" OnItemCommand="dtlSearchDetails_ItemCommand" OnItemDataBound="dtlSearchDetails_ItemDataBound">
<ItemTemplate>
<asp:ImageButton runat="server" ID="dtlImageCol" ImageUrl='<%# "~/uploads/thumbnails/" + Eval("ImageName") %>' /><br />
<asp:Label runat="server" ID="dtusage" Text='<%# Eval("usage") %>' Style="color: #CC121B;"></asp:Label><br />
<asp:ImageButton runat="server" ID="dtlImgDownload" CommandName="dtlImgDownload" CommandArgument='<%# Eval("ImageName") %>' ImageUrl="images/download.png" style="height:20px; width:20px;"/>
</ItemTemplate>
</asp:DataList>
All works well just the problem is that datalist is wrapped inside updatepannel and hence in order to download image at user end I need to register the control on the Page_Load event :
ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(dtlImgDownload);
since the dtlImgDownload is inside the datalist, I always get an error "The name dtlImgDownload doesn't exists in current context."
I tried several ways to find the control like dtlSearchDetails.FindControl("dtlImgDownload ")
but it always returns null.
I also tried
if(dtlSearchDetails.FindControl("dtlImgDownload ") != null)
{
ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(dtlSearchDetails.FindControl("dtlImgDownload "));
}
But same result, its always null.
Kindly point me to the right direction.
Firstly, you need to Bind the DataList. Then after this, you will need to loop through each of the DataListItems in the DataList
foreach ( DataListItem li in dtlSearchDetails.Items )
{
ImageButton imgButton = (ImageButton) li.FindControl("dtlImgDownload");
}
This will find the control within each DataListItem

Hilighting the current page in an asp.net 3.5 master page

In my project the master page contains a repeater that's used as a menu with an Xml file as the data source for the repeater.
<asp:Repeater ID="Admin_menus" runat="server">
<HeaderTemplate><div id="navmenu"><ul></HeaderTemplate>
<FooterTemplate>|</ul></div></FooterTemplate>
<ItemTemplate>
|<li>
<a href="<%# DataBinder.Eval(Container.DataItem, "url")%>"
class="link6" id="<%# DataBinder.Eval(Container.DataItem, "id")%>">
<strong>
<%# DataBinder.Eval(Container.DataItem, "title")%>
</strong>
</a>
</li>
</ItemTemplate>
</asp:Repeater>
urls in the xml file is as
<menuitems>
<item id="1" url="Employee.aspx" title="Employee" description="Employee" />
<item id="2" url="Location.aspx" title="Location" description="Location" />
</menuitems>
Here I want to change the CSS style of the current page in the menu.
One solution you can opt for is to handle the ItemCreated event of the <asp:Repeater> control. To do this you need to add an event handler:
In the .master markup:
<asp:Repeater ID="Admin_menus" runat="server" OnItemCreated="Admin_menus_ItemCreated">
<HeaderTemplate>
<div id="navmenu">
<ul>
</HeaderTemplate>
<FooterTemplate>
|</ul></div></FooterTemplate>
<ItemTemplate>
|<li runat="server" id="hyperlink"><a href="<%# DataBinder.Eval(Container.DataItem, "url")%>" class="link6" id="<%# DataBinder.Eval(Container.DataItem, "id")%>">
<strong>
<%# DataBinder.Eval(Container.DataItem, "title")%></strong> </a></li>
</ItemTemplate>
</asp:Repeater>
In the .master.cs codebehind:
protected void Admin_menus_ItemCreated(object sender, RepeaterItemEventArgs e)
{
// Ensure that the ItemCreated is not null, the first one (header?) gets
// returned null
if (e.Item.DataItem != null)
{
// Extract the "url" attribute from the Xml that's being used for
// databinding for this particular row, via casting it down to
// IXPathNavigable as the concrete type of e.Item.DataItem isn't available
// to us.
var currentUrl = ((IXPathNavigable)e.Item.DataItem).CreateNavigator().GetAttribute("url", "");
if (Request.Url.PathAndQuery.Contains(currentUrl))
{
// This just adds a background color of "red" to the selected
// menu item. What you actually do is entirely up to you
var hyperlink = (HtmlGenericControl) e.Item.FindControl("hyperlink");
hyperlink.Style.Add(HtmlTextWriterStyle.BackgroundColor, "red");
}
}
}
Note that I've added a runat="server" as well as an id="hyperlink" to the <li> tag in your ItemTemplate so that the code in the ItemCreated handler can find it easily to style it.
Perhaps one solution is to check the current page in your inline Eval code and add the "currentpage" class to the anchor
For simplicity I'm using Eval() instead of DataBinder.Eval()
<asp:Repeater ID="Admin_menus" runat="server">
<HeaderTemplate>
<div id="navmenu"><ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<a href='<%# Eval("url") %>' class='link6<%# Request.RawUrl.EndsWith(Eval("url").ToString()) ? " currentpage" : "" %>' id='<%# Eval("id")%>'><strong><%# Eval("title")%></strong></a>
</li>
</ItemTemplate>
<FooterTemplate>
</ul></div>
</FooterTemplate>
</asp:Repeater>
Instead of binding directly from your xml data to repeater, try to get the repeater databing event, and compare with the current page url and the each binding item to determine if the current item should be hi-lighted

Get the current bounded object in a ListView's ItemTemplate

I want to be able to get the current bound object in the ItemTemplate of a ListView control.
Here's an example of what I want to do:
<asp:ListView ID="UserList" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
//How can I get the current bound object in here?
</ItemTemplate>
</asp:ListView>
You can access it via the DataItem:
<%# DataBinder.Eval(Container.DataItem, "myPropertyName")%>'
If you wanted a textbox for example:
<asp:Label ID="MyProp" runat="server" Text='<%#Eval("myPropertyName") %>' />
If you just want the full object:
<%# (MyType)Container.DataItem %>

Send value of gridview row using hyperlink within it

I am not able to sent the value of the MachineID to another page using the hyperlink in gridview.
<!-- <asp:TemplateField HeaderText="FailedFiles"
SortExpression="NumFailedFilesOverSLA">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
Text='<%#Bind("NumFailedFilesOverSLA") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
I have tried putting
DataNavigateUrlFields="MachineID"
DataNavigateUrlFormatString="GetFilesFailed.aspx?id={0}"
but don't know why this is not working??
Please suggest...
thanks
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("Inventory_ID", "/default.aspx?ID={0}") %>'
Text="Details"></asp:HyperLink>
</ItemTemplate>
This should solve your problem. This is exactly how I used it.
If this doesn't work, then check that you are actually getting a value back from the DB for MachineID:
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("NumFailedFilesOverSLA") %>'
runat="server" DataNavigateUrlFields="MachineID"
DataNavigateUrlFormatString="GetFilesFailed.aspx?id={0}">
</asp:HyperLink>
First, try to put the default gridview in the page and attach it to the data source, so you can test if there is data to display.
If you are assigning the data source from code behind don't forget to call the DataBind() method after that.

Categories

Resources