asp:Image is not rendered at all inside asp:HyperLink - asp.net

I have this code in ASP.NET 4.5 / VS 2013
<asp:HyperLink ID="ht" runat="server" NavigateUrl='<%# Eval("Url") %>'>
<asp:Image ID="img" runat="server" CssClass="img-responsive"
ImageUrl='<%# Eval("Image") %>'></asp:Image>
</asp:HyperLink>
and the image inside hyperlink is not rendered at all, why?
I also have tried with static image link, but I get the same result.
I need the image inside hyperlink because I need a custom css class for the image

I tested your code and it renders the image properly. The worst case, you can use DataList.ItemDataBound Event to bind the data.
ASPX
<asp:DataList ID="DataList1" runat="server"
OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<asp:HyperLink ID="ht" runat="server">
<asp:Image ID="img" runat="server" CssClass="img-responsive"/>
</asp:HyperLink>
</ItemTemplate>
</asp:DataList>
Code Behind
public class MyClass
{
public string Url { get; set; }
public string Image { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataList1.DataSource = new List<MyClass>
{
new MyClass
{
Url = "http://www.google.com",
Image = "https://www.google.com/images/srpr/logo11w.png"
},
new MyClass
{
Url = "http://www.msn.com",
Image = "http://col.stb00.s-msn.com/i/80/53CAC6A10B6248682CF221B24A92.gif"
},
};
DataList1.DataBind();
}
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
var item = e.Item.DataItem as MyClass;
var ht = e.Item.FindControl("ht") as HyperLink;
ht.NavigateUrl = item.Url;
var img = e.Item.FindControl("img") as Image;
img.ImageUrl = item.Image;
}
}
If you use DataSet or DataTable, you need to cast DataItem to DataRowView. var dr = e.Item.DataItem as DataRowView;. look at this example.

The asp:HyperLink Web Control renders into an anchor tag, with anything between the <asp:HyperLink> ... </asp:HyperLink> becoming the the value for the Text attribute.
I would suggest you try using an asp:ImageButton instead for your purpose.
<asp:ImageButton ID="ibtnMyControl" CssClass="img-responsive" PostBackUrl="<%# Eval("Url") %>" ImageUrl="<%# Eval("Image") %>" />
ImageButton API reference

Related

add data to list with button in datalist or repeater

i cant add data to list in datalist please help me
i want to transfer some product to compare in other page
when i add value in page load it work but in repeater or datalist not work
this is my class
public class CAR
{
private int carid;
private string title;
public CAR(int carid, string title)
{
this.carid = carid;
this.title = title;
}
public int CARID
{
get
{
return carid;
}
}
public string TITLE
{
get
{
return title;
}
}
}
this is the html side
<asp:DataList ID="DataList1" OnItemCommand="DataList1_ItemCommand" runat="server" DataKeyField="id" DataSourceID="SqlDataSource1">
<ItemTemplate>
id:
<asp:Label Text='<%# Eval("id") %>' runat="server" ID="idLabel" /><br />
title:
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" /><br />
<asp:Button ID="Button1" runat="server" CommandName="compare" Text="Button" />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:takyabConnectionString %>' SelectCommand="SELECT * FROM [tbl_ad]"></asp:SqlDataSource>
<asp:Button ID="Button2" OnClick="Button2_Click" runat="server" Text="Button" />
and it is codebehind
ArrayList value = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Session.Add("v", value);
Response.Redirect("webform2.aspx");
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "compare")
{
value.Add(new CAR(1,"ok"));
}
}
The problem in your code is that, on the first button click, you are adding the value to the ArrayList, of which the state is not saved during the post back. Which means, on the Button2_Click event the array list will always be empty.
Change your value property something like this. Or Save the Arraylist value to the session in the DataList1_ItemCommand event itself
ArrayList value
{
get
{
ArrayList values = null;
if(ViewState["selectedValues"] != null)
values = (ArrayList)ViewState["selectedValues"];
else
{
values = new ArrayList();
ViewState["selectedValues"] = values;
}
return values;
}
}

Get value of gridview.selected.row[] with visible property = 'false'

Hi from this field in my gridview, I'd like to pass the id value when the select command field is clicked, but i don't want to have the id field visible so I have the visible property set to false; however, when I pass it on the SelectedIndexChanged event the value is "" yet when the visible property is set to "true" the text value passes fine. What is the correct way to do this?
<asp:BoundField DataField="Project_ID" Visible="false"/>
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
String ProjID = GridView1.SelectedRow.Cells[10].Text;
}
Try this:
.aspx
<asp:Gridview id="GridView1" runat="server" DataKeyNames="Project_ID" />
.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(gridView.SelectedDataKey != null)
{
var selectedId = GridView1.SelectedDataKey.Value;
}
}
Here you'll find more info about DataKeys in Gridviews: http://msdn.microsoft.com/de-de/library/system.web.ui.webcontrols.gridview.selecteddatakey(v=vs.110).aspx
I have done something like this in winform maybe can help you. That is what i used
int rowindex = dataGridView1.CurrentRow.Index;
string ProjID= dataGridView1.Rows[rowindex].Cells[10].Value.ToString();
you could use HiddenField inside your gridView ItemTemplate to keep the ID and use it in onrowcommand event, like below:
.aspx
<asp:GridView ID="gridProject" runat="server"
onrowcommand="gridProject_RowCommand">
<Columns>
<ItemTemplate>
<asp:HiddenField ID="hidProjectID" runat="server"
Value='<%# ((DataRowView)Container.DataItem)["Project_ID"] %>' />
<asp:Button ID="btnProject" runat="server" Text="use pro id"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
CommandName="DoSomething"></asp:Button>
</ItemTemplate>
</Columns>
</asp:GridView>
aspx.cs
protected void gridProject_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = 0;
GridViewRow gridRow;
GridView grid = sender as GridView;
try
{
switch (e.CommandName)
{
case "DoSomething":
index = Convert.ToInt32(e.CommandArgument);
row= gridProject.Rows[index];
string Id = ((HiddenField)row.FindControl("hidProjectID")).Value;
//do whatever you want here
break;
// and you can have as many commands as you want here
}
}
catch { //display error }
}

asp net repeater checkbox

I use a Checkbox in a Repeater, how can I know which
Checkbox have changed in OnCheckedChanged?
I have tried to set id then checkbox is binding data, but
it will not work. Hope someone can help me
Thanks
/Mats
Check the sender(Event Target) parameter
protected void Chb_Changed(object sender, EventArgs e)
{
if (sender != null)
{
CheckBox cb=(CheckBox)sender;
string clickedCheckBoxID=cb.ID;
}
}
Try following . Please note that we can also bind some primary column let's say "ID" column in some hidden field then get in code behind.
ASPX Side
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="sqldtasource" >
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" AutoPostBack="true" Text='<%#Bind("Name")%>' OnCheckedChanged="Chb_Changed"/>
<asp:HiddenField ID="hdn_ID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "ID") %>'/>
</ItemTemplate>
</asp:Repeater>
Code Behind :
protected void Chb_Changed(object sender, EventArgs e)
{
if (sender != null)
{
try
{
var hdnID = (HiddenField)checkBox.NamingContainer .FindControl("hf_ID");
if(hdnID != null)
{
string primaryFieldValue = hdnID.Value;
}
if (((CheckBox)sender).Checked)
{
Response.Write(((CheckBox)sender).Text + " is checked");
}
}
catch {
}
}
}

How to Add One event to each Item On A CheckboxList Asp.net

How Can I Add One Event to Each item On A CheckBoxList, pr example I Wanto to add One Click Event to check What Item Has been checked.
thanks in advance.
Each item in CheckBoxList is of type System.Web.UI.WebControls.ListItem and has no events defined.
That's a bit tricky with the CheckBoxList. Don't think there's a straight way to add an click-event to each item, since the ListItem-class doesn't have any events.
You could set AutoPostBack="true" on the CheckBoxList and check on page load which items are selected, but you wouldn't know easy which was the last one clicked.
Other solution is to get rid of the CheckBoxList and create just CheckBoxes and set the click-event on those to the same event-method. And there you could check the sender.
ASPX:
<asp:CheckBox ID="CheckBox1" Text="A" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox2" Text="B" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
<asp:CheckBox ID="CheckBox3" Text="C" OnCheckedChanged="CheckBox_Clicked" AutoPostBack="true" runat="server" />
Code behind:
void CheckBox_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine(((CheckBox)sender).Text);
}
Or you could make your own custom CheckBoxList that handles click-events on items.
OK. So I found this question/answer and it didn't help me out. While the provided answer is correct, there is an easy way to build a CheckBoxList-like control witha Repeater control.
Turns out that you can use a Repeater with an ItemTemplate with a CheckBox.
I have a complete explanation here: http://www.rhyous.com/2014/10/17/aspx-checkboxlist-alternative-that-allows-for-the-oncheckedchanged-event/
I also copied the needed data here in this answer:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxListExample._Default" %>
<%# Import Namespace="CheckBoxListExample" %>
<%# Import Namespace="CheckBoxListExample.Models" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="cb1" runat="server" AutoPostBack="true" OnCheckedChanged="RepeaterCheckBoxChanged"
Text="<%# ((CheckBoxViewModel)Container.DataItem).Name %>"
Checked="<%# ((CheckBoxViewModel)Container.DataItem).IsChecked %>" />
</ItemTemplate>
</asp:Repeater>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using CheckBoxListExample.Models;
namespace CheckBoxListExample
{
public partial class _Default : Page
{
private List<CheckBoxViewModel> _ViewModels;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var _ViewModels = new List<CheckBoxViewModel>
{
new CheckBoxViewModel {Name = "Test1", IsChecked = true},
new CheckBoxViewModel {Name = "Test2"},
new CheckBoxViewModel {Name = "Test3"}
};
Repeater1.DataSource = _ViewModels;
Repeater1.DataBind();
}
}
protected void RepeaterCheckBoxChanged(object sender, EventArgs e)
{
var cb = sender as CheckBox;
if (cb == null) return;
if (cb.Checked)
{
// Insert
}
else
{
// Delete
}
}
}
}
CheckBoxViewModel
namespace CheckBoxListExample.Models
{
public class CheckBoxViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
}

Using Repeater for an updateable form

I have a list of parameter names for which I want a user to type in some values, so I do this:
<div>
<asp:Repeater runat="server" ID="rptTemplateParams" EnableViewState="true">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:Label runat="server"><%#Container.DataItem%></asp:Label>
<asp:TextBox runat="server" ID="textParamValue"></asp:TextBox>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
<asp:Button runat="server" ID="Send" Text="Send Email" OnClick="Send_Click" />
and on server side:
void Page_Load(...)
{
rptTemplateParams.DataSource =Params; // Params is List<string>
rptTemplateParams.DataBind();
}
public void Send_Click(object sender, EventArgs e)
{
ParamDict = new Dictionary<string, string>();
foreach (RepeaterItem item in rptTemplateParams.Items)
{
if (item.ItemType == ListItemType.Item)
{
TextBox textParamValue = (TextBox)item.FindControl("textParamValue");
if (textParamValue.Text.Trim() != String.Empty)
{
// IT NEVER GETS HERE - textParamValue.Text IS ALWAYS EMPTY!!!
ParamDict.Add(item.DataItem.ToString(), textParamValue.Text);
}
}
}
}
As I put in the comment, i can't retrieve text box values - they are always empty. Am I retrieving those in the wrong place?
Thanks!
Andrey
Try modifying your page_load like this
if(!Page.IsPostBack)
{
rptTemplateParams.DataSource =Params; // Params is List<string>
rptTemplateParams.DataBind();
}
The databinding wipes out existing controls and replaces them with new blank controls. You only want to databind when necessary.
try this:
void Page_Load(...)
{
if (!IsPostBack)
{
rptTemplateParams.DataSource =Params; // Params is List<string>
rptTemplateParams.DataBind();
}
}

Resources