Datalist name not declared when using Code Behind. aspx.vb - asp.net

I'm a totally newbie to .NET programming, and trying to get some stuff off the ground.
I've run some code which extracts data from a database and presents it into a Datalist. It works fine when the script is on the aspx file, but when I transfer it to a code behind I get the following error
Compiler Error Message: BC30451: Name 'showIt' is not declared.
(showIt is the ID of the Datalist)
Obviously, the Datalist markup is in my aspx page, and the script is in the code behind .vb file.
As I say, it all works when the scripts are all on the one .aspx file.
The code in the code behind is: (I've skipped the SQL and connection strings to keep this post concise)
Partial Public Class Data
Inherits System.Web.UI.Page
Sub Page_Load(sender As Object, e As EventArgs)
Dim objDataReader As OdbcDataReader
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
showIt.DataSource = objDataReader
showIt.DataBind()
objDataReader.Close()
end sub
end class
The aspx file looks like this: (again simplified, basic HTML markup etc removed)
<%# Page Language="VB" AutoEventWireup="true" CodeFile="dataOut.aspx.vb" Inherits="_Default"%>
<form id="form1" runat="server">
<asp:DataList ID="showIt" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
<ItemTemplate>
<div style="width:300px; display:inline-block; height: 200px; overflow:hidden">
<div style="width:100%; background:#880000; border-bottom: solid 1px black"><%# DataBinder.Eval(Container.DataItem, "item") %></div>
<br />
<%# Data.stockDisplay(Eval("shopstock"))%>
<div style="clear: both"><%# Left(DataBinder.Eval(Container.DataItem, "description"),150) %></div>
</div>
</ItemTemplate>

Ah ha.... I've fixed it!
needed to declare the DataList before the function so it became publicly available... or at least I think that was the issue, it works now anyway
Protected WithEvents showIt As System.Web.UI.WebControls.DataList
I now have other issues... that can go in another question though!

Related

How to databind a local variable in an ASPX template?

I have a UserControl named SlidingScaleTableReadonly with a bindable public member ScaleEntries, which take a List of struct instances. In the parent page, these lists are stored in a dictionary (InsulinSlidingScaleProtocolEntries), and I must render one SlidingScaleTableReadonly for each entry in this dictionary. Here's my template code so far:
<%# Register TagPrefix="uc" TagName="SlidingScaleTableReadonly" Src="~/Patient/SlidingScaleTableReadonly.ascx" %>
<asp:Content ContentPlaceHolderID="phContent" runat="server">
<h1>Échelles</h1>
<% For Each drug In InsulinSlidingScaleProtocolEntries %>
<h2><%= drug.Key %></h2>
<uc:SlidingScaleTableReadonly runat="server" ScaleEntries="<%# drug.Value %>" />
<% Next %>
</asp:Content>
My problem is at line 7:
BC30451 'drug' is not declared. It may be inaccessible due to its protection level.
If I replace drug.Value with a property available in code behind, the new variable can be found. I'm guessing it's not possible to directly data-bind local variables in ASPX? If that's the case, how can I use data-binding inside an iteration?
Edit - Changing the provenance of the bound value
I've changed the code a bit. Right after the "For Each" loop opening, a code-behind property named CurrentDrug is reassigned with the value of drug.Value, and uc:SlidingScaleTableReadonly get it's ScaleEntry from that new property. But that doesn't work either, the reassignment won't do shuck and ScaleEntry is always Nothing (or whatever initial value I gave to CurrentDrug).
Here's the new template:
<%# Register TagPrefix="uc" TagName="SlidingScaleTableReadonly" Src="~/Patient/SlidingScaleTableReadonly.ascx" %>
<asp:Content ContentPlaceHolderID="phContent" runat="server">
<h1>Échelles</h1>
<% For Each drug In InsulinSlidingScaleProtocolEntries
CurrentDrug = drug.Value %>
<h2><%= drug.Key %></h2>
<uc:SlidingScaleTableReadonly runat="server" ScaleEntries="<%# CurrentDrug %>" />
<% Next %>
</asp:Content>
And code-behind:
Public CurrentDrug As List(Of ScaleEntry)
Public Property InsulinSlidingScaleProtocolEntries As Dictionary(Of String, List(Of ScaleEntry))
'...
End Property
Edit - (Not) a solution: Stopped using aspx templates
I have to move on, and it seems like I'm not going to do any progress with aspx templates. I've rewritten the page so the UserControl is declared and inserted in code-behind. I think that's not how one should build an interface, that's not where that kind of logic should be place but I really want to move on.
Here's the new template code:
<asp:Content ContentPlaceHolderID="phContent" runat="server">
<h1>Échelles</h1>
<div id="scaleContainer" runat="server"></div>
</asp:Content>
Code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each prescription In InsulinSlidingScaleProtocolEntries
Dim label As New HtmlGenericControl("h2") With {
.InnerText = prescription.Key
}
Dim table = CType(Page.LoadControl("~/Patient/SlidingScaleTableReadonly.ascx"), SlidingScaleTableReadonly)
table.ScaleEntries = prescription.Value
scaleContainer.Controls.Add(label)
scaleContainer.Controls.Add(table)
Next
End Sub
If you have a better solution, I'll be happy to see it.

asp.net output from a SOAP page location using response.write

I hope someone can help. I created a webservice and it returns XML via SOAP fine and well. It transforms fine with XSLT and I return the HTML to a ASP VB.net webform.
I call the functions in the code behind with a button.
Everything works great except the transformed output always ends up at top of the page. I return the result to a label, put the label in a different contentplaceholder but it always is on top. I want the input items(text box) and button to float at the top.
Here is the very simple main webform - plus a bit from where the results are coming from.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="WebForm1.aspx.vb" Inherits="WS_NewCar.WebForm1" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<p>
<img src="images/barner.jpg" style="width: 508px; height: 198px; margin-left: 280px" /></p>
<p>
</p>
<p>
<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
</p>
<p>
</p>
<p>
</p>
<p>
<br />
Click here for SOAP request. <asp:Button ID="btnConvert" runat="server" Text="Search" />
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<asp:Label ID="lblMake" runat="server" Text="Please enter vehicle make"></asp:Label>
</asp:Content>
Dim sr As New StreamReader(memoryStream)
response.Write(sr.ReadToEnd())
sr.Close()
End Function
Protected Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
lblMake.Text = callWS(txtInput.Text)
End Sub
Response.Write(sr.ReadToEnd()) will always render at the top of the page. It is called before the page is rendered. Try changing it by adding a label where you want the output to appear and do the following in your page_load
label1.Text = sr.ReadToEnd()

How do I "print" an image to a ASP.NET update panel page?

I create a chart, and save it in the path server.mappath("/images/chart/chartname.png"), and if I go to the path, the image is there, and I can open it on my computer, but what I would really like to do is display the image on the page after I create it, preferably asynchronously. I've tried putting a asp:image control in the update panel and changing the url, but that doesn't work. I've tried a bunch of different ways, if someone could point me to the right direction, that would be great. I won't post any code simple because what I have so far IS working. Once I start attempting to print the image I'll post snippets if I have answers.
Edit: Here is some code
The button event that starts the whole thing:
Protected Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
Dim worker As New backgroundWorker
'Check input
worker.RunWorker({})
Session("worker") = worker
Timer1.Enabled = True
End Sub
This starts the worker, which generates the chart fine, and starts the timer which is used to update the panel. Eventually in that code, this happens
Dim imgpath As String = Server.MapPath("images/chart/test.png")
chart.SaveImage(imgpath, ChartImageFormat.Png)
chartImg.ImageUrl = "~/images/chart/test.png"
Now, I know that the panel is being updated after this code is executed, because I output some messages to a multiline textbox, and they do appear. All these controls are also in the contentTemplate of the updatePanel.
Setting the ImageUrl property of an ASP.Net image control, while within and update panel, should do the trick without having to use Javascript, although that method can be very efficient. UpdatePanels tend to be "heavy", that is the ScriptManager, UpdatePanel, and ASP.Net ViewState tend to send a lot of information back and forth via their AJAX methods. You can see what I mean by using Fiddler to watch your web traffic.
That being said, I was able to achieve the desired effect in the following manner. I have two static images, Image1.jpg and Image2.jpg, but it should work with your dynamically generated image, as long as the URL is correct.
Here's the text of my ASPX page:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Image1.jpg" Width="300"></asp:Image><br />
<asp:Button runat="server" ID="btnSwitchImage" Text="Switch" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
And here is the code-behind:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e )
{
btnSwitchImage.Click += new EventHandler( btnSwitchImage_Click );
}
void btnSwitchImage_Click( object sender, EventArgs e )
{
Image1.ImageUrl = "~/Image2.jpg";
}
}
As long as the button and image controls are within the UpdatePanel's ContentTemplate everything should be relayed via AJAX. Once again, use Fiddler to confirm this.
If this example works for you but you still can't get your application working try posting some code in your question. It might help everyone analyze the problem directly.
As per my experience uploading of files does not work in asynchronous mode.You should use Jquery library to upload file asynchronously.
Check this link.
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
I do not know ajax but you can do it with the help of javascript. Here is the code I tested on my system which works fine.
<body>
<p>
welcome to judge site</p>
<form id="form1" runat="server">
<script language="javascript" type="text/javascript">
function PrintImage()
{
printWindow = window.open ("", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
printWindow.document.write("<div style='width:100%;'>");
printWindow.document.write("<img id='img' src='" + document.getElementById('iconId').src + "'/>");
printWindow.document.write("</div>");
printWindow.document.close();
printWindow.print();
}
</script>
<div>
<img id="iconId" alt="photo" src="iconId.png" style="width: 500px; height: 360px" /><br />
<input type="button" id="btnPrint" value="Print Image" onclick="PrintImage()" />
</div>
</form>
There are other more examples you can find on following link (Above code is also from this source but edited by me to make it work on my system)
Visit http://forums.asp.net/p/1463001/3369521.aspx

ASP.NET form using label

I have to create an asp.net form using label. I found an example for this task and tried to run it but nothing from the expected result appeared. Do you have any idea what else should be done to run it? (I'm still at the very beginnig of asp.net.)
Here is the code:
<%# Page Language="vb" %>
<script runat="server">
Sub submit(Sender As Object, e As EventArgs)
label1.Text=txt1.Text
End Sub
</script>
<html>
<body>
<form runat="server">
Write some text:
<asp:TextBox id="txt1" Width="200" runat="server"/>
<asp:Button id="b1" Text="Copy to Label" OnClick="submit" runat="server"/>
<p><asp:Label id="label1" runat="server"/></p>
</form>
</body>
</html>
Please check the default access modifier for your function(SUB).
In c# we use protected and from MSDN
Class members, including nested classes and structs, can be public,
protected internal, protected, internal, or private. The access level
for class members and struct members, including nested classes and
structs, is private by default. Private nested types are not
accessible from outside the containing type.
So try with Friend access modifier for VB.Net.

How to use Eval in codebehind to set Page.Title

I have a SQLDataSource that is bound to a ListView control but I want to place parts of the bound record into the HTML TITLE attribute. Here is my codebehind file that I want to change so it can use Eval to construct a dynamic TITLE based on the data content:
Public Partial Class zShowAd
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Title = " Dynamically set in ASPX page"
'how to use Eval here instead of the above constant ??
End Sub
End Class
Here is the corresponding .aspx file:
<%# Page Language="vb" AutoEventWireup="false" MasterPageFile="~/zSEO.master"
CodeBehind="zShowAd.aspx.vb" Inherits="Zipeee.zShowAd" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div>
<asp:ListView ID="ShowAd" runat="server" DataSourceID="aPosting">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<div>
<div id="wrapper">
<div id="header"></div>
<div id="main">
<div id="nav"> AdID: <%#Eval("AdID")%></div>
<div id="extras">Price: <%#Eval("Price")%></div>
<div id="content"> <%#Eval("AdDesc")%></div>
</div>
<div id="footer"></div>
</div>
</div>
</ItemTemplate>
</asp:ListView>
<asp:sqldatasource runat="server" id="aPosting"
ConnectionString="<%$ ConnectionStrings:ZIPeeeConnectionString2 %>"
SelectCommand="spGetAdByID" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:QueryStringParameter Name="AdId" QueryStringField="a" Type="String" />
</SelectParameters>
</asp:sqldatasource>
</div>
</asp:Content>
You can call a method (Sub) of the page's code behind by putting the following somewhere inside the ItemTemplate of your ListView:
<%# SetPageTitle(Eval("SomeProperty")) %>
Then in your code behind (sorry it's in C#):
protected void SetPageTitle(object title)
{
this.Title = title.ToString();
}
Alternatively, you can also pass the complete data item, instead of just one property:
<%# SetPageTitle(Container.DataItem) %>
Update (to answer your comment):
<%# ... %> is a so-called data-binding expression. It only works inside of a data-bound control (the ListView in your example) and it always works with the current record (typically you display more than one record in a data-bound control like the ListView).
So when you use <%# Eval("Price") %>, you are displaying the value of the current record's "Price" column. If your query, would return more than one record, then this would be executed for each record, and when setting the page title (as shown above), the page's title would be the value from the last record.
On the other hand <%= ... %>, is just a normal server-side code snippet (don't know if there is a specific name for it), which does not know about the data-binding context (e.g. which is the current record).
Please see the following question for more details: When should I use # and = in ASP.NET controls?

Resources