Displaying photo from photopath in eval repeater ASP.NET - c#

I am trying to display images in eval repeater but it doesn't work. When I put simply div instead of asp:Repeater I get the image path. (I have no problem with SQL side)
Can anyone tell what's wrong with this code?
Thanks.
<div class="wrapper">
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl="<%# Eval("PresidentPhotoPath") %>" runat="server" />
</ItemTemplate>
</asp:Repeater>
</div>
SqlConnection cnn = new SqlConnection("Initial Catalog=whitehouse;Data Source=localhost;Integrated Security=SSPI;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT PresidentPhotoPath FROM presidents", cnn);
SqlDataReader dr = cmd.ExecuteReader();
Repeater1.DataSource = dr;
Repeater1.DataBind();
cnn.Close();
}
}

The ImageUrl syntax here is wrong:
ImageUrl="<%# Eval("PresidentPhotoPath") %> "
You have double quotes inside of double quotes, change the outer quotes to be single quotes, like this:
ImageUrl='<%# Eval("PresidentPhotoPath") %>'
As for your issue with prepending Images/ before the file name, I would recommend using a code-behind method to build the string for you, like this:
protected string BuildPath(string photoPath)
{
return "Images/ + photoPath;
}
Note: Consider naming this something more useful than BuildPath as that is fairly generic, just picked that name because nothing better came to mind immediately.
Now in your markup you can just call the method, like this:
ImageUrl='<%# BuildPath(Eval("PresidentPhotoPath")) %>'
I recommend this approach for the following reasons:
The markup does not contain any complex logic whatsoever, just a method call with the Eval() value
It is easier to debug the logic versus embedded code blocks
You can leverage the power of Visual Studio compiler to catch syntax errors at compile-time versus run-time errors when the logic is embedded into the binding syntax of the markup

Related

How can i solve this; Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. The system cannot find the file specified

I want to mask for phone number. I tried to use Ajax Control Tool Kit - MaskedEditExtender for this. I downloaded Ajax Control Tool Kit from Nuget. On the Aspx page, I added the code I found on the internet, where the error was given below. But I don't know how to solve this error. Can you help me?
Ok, so say we want to autocomplete a text box (against say the database).
so, we would first do a nuget of ajaxtoolkit.
Then, we drop a text box on a form.
We should see this - say this markup:
Then we now click on the text box in the designer.
And then
so, now our markup is this:
<h3>enter hotel Name</h3>
<asp:TextBox ID="txtHotel" runat="server"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="txtHotel_AutoCompleteExtender"
runat="server" BehaviorID="txtHotel_AutoCompleteExtender" DelimiterCharacters=""
TargetControlID="txtHotel"
ServiceMethod = "SearchCustomers"
MinimumPrefixLength = "1"
CompletionInterval="100"
EnableCaching="false"
CompletionSetCount="10" >
</ajaxToolkit:AutoCompleteExtender>
Note that I displayed the property sheet, and filled out the above values.
(remove the ServicePath="" - you don't need it).
so, now our code behind:
// using System.Web.Services;
[WebMethod()]
public static List<string> SearchCustomers(string prefixText, int count)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL
= "select HotelName FROM tblHotels WHERE HotelName like #SearchText + '%' ORDER BY HotelName";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
cmd.Parameters.Add("#SearchText", SqlDbType.NVarChar).Value = prefixText;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
customers.Add(sdr["HotelName"].ToString());
}
}
}
return customers;
}
And now we get this:
So, you create a web method in the code behind.
Edit: you wanted a mask
Somehow, I posted the wrong info and answer for this quesiton.
However, for a edit mask?
Then again, drop in a text box, extender - edit mask.
So, say this:
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
and then:
We now have this for the markup:
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
<ajaxToolkit:MaskedEditExtender ID="TextBox1_MaskedEditExtender"
runat="server" BehaviorID="TextBox1_MaskedEditExtender"
TargetControlID="TextBox1" Mask="(999)-999-9999" />
Doing above, should insert (add) to the page at the top this:
<%# Register assembly="AjaxControlToolkit"
namespace="AjaxControlToolkit"
tagprefix="ajaxToolkit" %>
And now when we enter that textbox, you get this:

How to use Server Side variables on Markup

I want to use Session variable's value on the markup. This is the code written on UserContorl.ascx, file on NavigateUrl I want to send the Username which is stored in the session variable. I don't want to set NavigateUrl value on PageLoad function for some reason.
Note the code gives the error: The server tag is not well formed.
<asp:Panel ID="pnlMenuItems" runat="server" HorizontalAlign="Left">
<asp:HyperLink ID="LinkLogout" runat="server" NavigateUrl="~/logout/"+
<%= HttpContext.Current.Session["UserName"].ToString(); %>> CssClass="pnlMenuItems"
ForeColor="#666666">Logout</asp:HyperLink>
</asp:Panel>
You can bind data within server tags. e.g.
<asp:HyperLink ID="LinkLogout" runat="server"
NavigateUrl="<%# LogoutUrl %>"
CssClass="pnlMenuItems"
ForeColor="#666666">Logout</asp:HyperLink>
then in your code behind:
protected string LogoutUrl {
get {
return "~/logout/" + HttpContext.Current.Session["UserName"].ToString();
}
}
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) { DataBind(); }
}
The NavigateUrl gets set during the call to DataBind() using this method. In my example, the value would get set during page load, but you wouldn't have to specifically do it. If you need it to happen at a different time during the page lifecycle, you can try calling DataBind() during a different event.
How about:
<asp:Panel ID="pnlMenuItems" runat="server" HorizontalAlign="Left">
<asp:HyperLink ID="LinkLogout" runat="server"
NavigateUrl="<%# "~/logout/" + HttpContext.Current.Session["UserName"].ToString() %>"
CssClass="pnlMenuItems"
ForeColor="#666666">Logout</asp:HyperLink>
</asp:Panel>

how to pass values between two repeateres on the same page

I have two repeaters that looks like this :
Arrange By: Name | Age | Area
what I want to do now is to populate the second repeater from the database with the alphabet, and if the age was clicked then the second repeater gets populated from the database with some age ranges!
I already implemented my idea by placing a hyperlink in the first repeater, that passes -using it's NavigateUrl property- a url for the same page but with some querystring values!
I've been told that querystrings are used for passing values from one page to another, not the same page...and also I wanted to use some AJAX (script manager and update panel) but turns out that I have to use some server control within my repeater instead of html controls so it could be able to post back to the server
I hope you'd help me with a good implementation for passing the value from repeater1 to repeater2 and if you think that I've stated anything wrong Please Corret Me!
Thanks in advance :)
EDIT
my.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string commandString1 = "SELECT [arrange_by_id], [arrange_by] FROM [arrange_by]";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString))
{
using (SqlCommand cm = new SqlCommand(commandString1, cn))
{
cn.Open();
using (SqlDataReader dr = cm.ExecuteReader())
{
ArrangeBy_rpt.DataSource = dr;
ArrangeBy_rpt.DataBind();
}
}
}
}
void arrange_lnkbtn_command(object sender, CommandEventArgs e)
{
Label1.Text = (e.CommandArgument).ToString();
}
my.aspx
<asp:Repeater ID="ArrangeBy_rpt" runat="server">
<ItemTemplate>
<asp:LinkButton id="arrange_lnkbtn" OnCommand="arrange_lnkbtn_command" CommandArgument='<%#Eval("arrange_by_id") %>' runat="server">
<%# Eval("arrange_by") %>
</asp:LinkButton>
</ItemTemplate>
<SeparatorTemplate> | </SeparatorTemplate>
</asp:Repeater>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Compilation Error
Compiler Error Message: CS1061: 'ASP.sortingcontrol_ascx' does not contain a definition for 'arrange_lnkbtn_command' and no extension method 'arrange_lnkbtn_command' accepting a first argument of type 'ASP.sortingcontrol_ascx' could be found (are you missing a using directive or an assembly reference?)
Line 4: <asp:Repeater ID="ArrangeBy_rpt" runat="server">
Line 5: <ItemTemplate>
Line 6: <asp:LinkButton id="arrange_lnkbtn" OnCommand="arrange_lnkbtn_command" CommandArgument='<%#Eval("arrange_by_id") %>' runat="server">
Line 7: <%# Eval("arrange_by") %>
Line 8: </asp:LinkButton>
There's nothing wrong per se with passing data to the same page using the querystring, though it shouldn't be used for sensitive data that the user might change by "hacking" the URL. However, it's not the standard way of doing things in ASP.NET WebForms, since it won't postback the values of any other controls on the page (and hence they won't retain their state without you manually having to re-populate them on every page load). But if this is not a problem for you, feel free to stick with querystring.
Howecer, generally you would use a server-side control like an asp:Button or an asp:LinkButton and then handle their OnClick event. However, to pass data with one you can use the CommandName and CommandArgument properties of the button and then handle the OnCommand event.
<asp:LinkButton id="LinkButton1"
Text="Click Me"
CommandName="Age"
CommandArgument="18"
OnCommand="LinkButton_Command"
runat="server"/>
In code-behind:
void LinkButton_Command(Object sender, CommandEventArgs e)
{
var data = GetData(e.commandArgument); // implement a method that gets your data filtered by the argument passed from the button
Repeater2.DataSource = data;
Repeater2.DataBind();
}

DataBinder.Eval in c#

Hi anybody know how to use databinder.eval in c#
Actually I've tried this
LinkButton lnkName = new LinkButton();
lnkName.CommandArgument = DataBinder.Eval("object","<%#COURSE_ID%>");
it is showing error. Whats the wrong with this?
You can't use Eval in the code behind of an aspx page.
this:
lnkName.CommandArgument = DataBinder.Eval("object","<%#COURSE_ID%>");
should be this:
lnkName.CommandArgument = YOUR_OBJECT_PROPERTY_HERE;
To fill in YOUR_OBJECT_PROPERTY_HERE you either need to specify the object.property etc like normal in C# code, or you'll have to use reflection to get the property value from the object (which is what eval does for you).
Here is a link showing how to use reflection to get the property information from an object. You can use it to duplicate how eval works if you need to: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6099345.html
Link to DataBinder Eval Method: http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx
How the DataBinder Eval Method works (and why the author thinks it should be avoided) http://weblogs.asp.net/jgalloway/archive/2005/09/20/425687.aspx
For Example in design page you can use like:
<asp:Button ID="btnEdit" CommandName="Edit"
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CssClass="cursor_hand" runat="server" Text="Edit" />
Code Behind:
int rowIndex = int.Parse(e.CommandArgument.ToString());
if (e.CommandName.Equals("Edit"))
{
//do something
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
string h = DataBinder.Eval(e.Row.DataItem, "ColumnName").ToString();
}
}
You should use Eval expression and <% %> in *.aspx code not with C# code.

Binding Eval with an ImageURL in ASP.NET

I'm trying to bind an image using Eval() with VB.NET and ASP.NET, but am running into issues:
Code snippet
<bri:ThumbViewer Id="Th1" runat="server"
ImageUrl='<%# Eval("Name", "~/SiteImages/ram/3/{0}") %>'
Height="100px"
Width="100px"
/>
I set strImagePath in the code-behind as:
strImagePath ="~/SiteImages/ram/3/"
How can I replace:
~/SiteImages/ram/3/{0}
with the variable strImagePath?
simply use
<asp:Image id="abc" ImageUrl =<%# string.Format("~/SiteImages/ram/3/{0}",Eval("imagepath"))%>
imagepath could be from datatable or cs
I personally prefer to do these things in the codebehind directly like
<bri:ThumbViewer ID="thumbViewer" runat="server" ... />
and then in the codebehind you have some initialize or DataBind() method where you write
thumbViewer.ImageUrl= Path.Combine(ImagePath, Name); //or something similar, you have to check
This because especially when you develop in a team it is quite inconvenient and error-prone if people do some bindings in the ASPX code directly using Eval(...) and some in the codebehind. I prefer using the codebehind because then you immediately see what's going on on the page by just looking on your code, while your ASPx code is just for layout, definition of controls (with properties) etc...
string strImagePath = "aPage.aspx";
string pathFormat = "~/SiteImages/ram/3/{0}";
string path = String.Format(path, strImagePath);
Thats a little bit verbose, but you get the idea. What you're looking for is the String.Format method.
You can read more about it over at MSDN -> String.Format
So in your case that would be:
<bri:ThumbViewer Id="Th1" runat="server" ImageUrl='<%# Eval("Name", String.Format("~/SiteImages/ram/3/{0}", strImagePath)) %>' Height="100px" Width="100px"/>
as long as strImagePath is set to public or protected in your codebehind
Can you just write (and forgive me if this is wrong) if it is constant:
<bri:ThumbViewer ImageUrl='~/SiteImages/ram/3/<%# Eval("Name")%>' Height="100px" Width="100px" Id="Th1" runat="server"/>
And if it isn't:
<bri:ThumbViewr ImageUrl='<#Eval("ImagePath + Name") %>' ... />
//And in your codebehid:
public property ImagePath { get; set; }
...
ImagePath = "...";

Categories