Populate Literal elements with the results of a SqlDataSource query - asp.net

I have what is possibly a very simple question yet the answer is escaping me completely. I'm new to ASP.NET (vb) but I have a solid Classic ASP/VB background.
I have a relatively simple database which contains just four columns (Language, SiteFooterPrivacyPolicy, SiteFooterTermsAndConditions, SiteFooterCopyright). I wish to perform a query which will return just 1 row.
Here is the main page so far (along with the SQL SELECT statement):
<%# Page Language="VB" AutoEventWireup="false" CodeFile="dbtest1.aspx.vb" Inherits="dbtest1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="MyLanguageDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:customer_support_devConnectionString %>"
ProviderName="<%$ ConnectionStrings:customer_support_devConnectionString.ProviderName %>"
SelectCommand="SELECT [SiteFooterPrivacyPolicy], [SiteFooterTermsAndConditions], [SiteFooterCopyright] FROM [language_file_2] WHERE ([Language] = 'French')">
</asp:SqlDataSource>
<br />
<br /><b>Literal1PrivPolicy:</b> <asp:Literal ID="Literal1PrivPolicy" runat="server"></asp:Literal>
<br /><b>Literal2TermsConds:</b> <asp:Literal ID="Literal2TermsConds" runat="server"></asp:Literal>
<br /><b>Literal3Copyright:</b> <asp:Literal ID="Literal3Copyright" runat="server"></asp:Literal>
<br />
</div>
</form>
</body>
</html>
And so far I have this code behind (which does not work) but hopefully it'll explain far better than I can, what I am trying to achieve:
Partial Class dbtest1
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim dv As New Data.DataView
dv = MyLanguageDataSource.Select(DataSourceSelectArguments.Empty)
Literal1PrivPolicy.Text = dv.Table.Rows("SiteFooterPrivacyPolicy").ToString()
Literal2TermsConds.Text = dv.Table.Rows("SiteFooterTermsAndConditions").ToString()
Literal3Copyright.Text = dv.Table.Rows("SiteFooterCopyright").ToString()
End Sub
End Class
Hopefully from that you can see what I'm trying to do. I basically need my Literal elements populated with the correct column returned from my database query.

I think you're trying to access the rows by name, when you should be accessing the first row's columns by name, e.g:
Literal1PrivPolicy.Text = dv.Table.Rows(0)("SiteFooterPrivacyPolicy").ToString()

Related

ServerClick not working on IP Address using Internet Explorer

My superior asked me to redirect or always use an IP based address for the web application that I created.
Ex: Instead of using http://www.google.com, the project should use
http:/ /173.194.127.46
In this way, the computers on our network could visit the webportal directly.
Unfortunately, when I use the IP, the server script on code behind doesn't work. I tried to create a simple one to prove it right.
Default.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btnClick" Text="Test Click" />
<asp:Label ID="Label1" runat="server" Text="Label" />
<button runat="server" id="btnClick2">Test Click 2</button>
</div>
</form>
</body>
</html>
Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnClick_Click(sender As Object, e As System.EventArgs) Handles btnClick.Click
Label1.Text = "Clicked from ASP Button"
End Sub
Protected Sub btnClick2_ServerClick(sender As Object, e As System.EventArgs) Handles btnClick2.ServerClick
Label1.Text = "Clicked from HTML Button"
End Sub
End Class
The code on HTML Button does not work, like it doesn't have a script.
There are html tags I placed inside the HTML Button so replacing to ASP Button will not solve it.
Is there a way I can make the codes on HTML Button work?
Update: It is working on the latest version of Google Chrome and Mozilla Firefox
I solved it but I need further testing!
Here's what I've done.
<%# Page Language="VB" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">.hid{display: none;}</style>
</head>
<body>
<form id="form1" name="form" runat="server">
<div>
<asp:Button runat="server" ID="btnClick" Text="Test Click" />
<button runat="server" id="btnClick2">Test Click 2</button>
<button runat="server" id="btnClick3" onclick="document.getElementsByTagName('form')[0].btnHidden.click();return false;">Test Click 3</button>
<asp:Button runat="server" CssClass="hid" ID="btnHidden" />
<br /><asp:Label ID="Label1" runat="server" Text="Label" />
</div>
</form>
<script type="text/VB" runat="server">
Protected Sub btnClick_Click(sender As Object, e As System.EventArgs) Handles btnClick.Click
Label1.Text = "Clicked from ASP Button"
End Sub
Protected Sub btnClick2_ServerClick(sender As Object, e As System.EventArgs) Handles btnClick2.ServerClick
Label1.Text = "Clicked from HTML Button"
End Sub
Protected Sub btnHidden_Click(s As Object, e As EventArgs) Handles btnHidden.Click
Label1.Text = "Clicked from ASP Button via HTML Button"
End Sub
</script>
</body>
</html>
What I did is add ASP Button that will trigger the server script. Then on the HTML button, I added onclick event that will perform a click on ASP Button.

Why does this code work in a stand-alone page but when used with a Master Page it fails with: Object reference not set to an instance of an object

I have a very simple page which works well - until I drop the code in to a new page which is using a Master Page. I then get the error:
Object reference not set to an instance of an object
My simple (stand-alone) working page is:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="emaillookuptest.aspx.vb" Inherits="emaillookuptest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="LoginDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:customer_support_devConnectionString %>"
ProviderName="<%$ ConnectionStrings:customer_support_devConnectionString.ProviderName %>"
SelectCommand="SELECT [id_staff], [semail] FROM [staff] WHERE ([semail] = ?)">
<SelectParameters>
<asp:FormParameter FormField="TextBoxEmailAddress" Name="semail"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<p>
Email Address:
<asp:TextBox ID="TextBoxEmailAddress" runat="server" MaxLength="100"
Width="200px"></asp:TextBox>
</p>
<asp:Button ID="LoginButton" runat="server" Text="Log In" />
<br />
<asp:Label ID="LabelLoginResults" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
And the code behind:
Partial Class emaillookuptest
Inherits System.Web.UI.Page
Protected Sub LoginButton_Click(sender As Object, e As System.EventArgs) Handles LoginButton.Click
Dim dv As New Data.DataView
dv = LoginDataSource.Select(DataSourceSelectArguments.Empty)
Dim c As Integer = dv.Count.ToString()
If c <> 0 Then
LabelLoginResults.Text = "Staff ID: " & dv.Table.Rows(0)("id_staff").ToString()
Else
LabelLoginResults.Text = "That email address was not found"
End If
End Sub
End Class
As you can see, straight forward enough.
However, as soon as I try and use this code with an existing Master Page, I'm presented with the error "Object reference not set to an instance of an object" on line:
Dim c As Integer = dv.Count.ToString()
The only possible cause that I can see for this is within the master page I have the following:
Dim dv As New Data.DataView
dv = MyLanguageDataSource.Select(DataSourceSelectArguments.Empty)
LitSiteFooterCopyright.Text = dv.Table.Rows(0)("SiteFooterCopyright").ToString()
As you can see, I am referecing two different data sources ('LoginDataSource' in my new page and 'MyLanguageDataSource' in my Master Page).
Is the issue because I am using either 'dv' or 'Data.DataView' or 'DataSourceSelectArguments' twice? Once within the master page and once again in my new emaillookuptest.aspx page?
If so, suggestions for either a workaround or the correct way to do this would be welcomed :)
Update: If I remove ALL the code behind from the Master Page, I still get the same error. This just confuses me even more now as the code works perfectly on it's own, yet if I drop it in to an empty Master Page arrangement I get the same error at line: Dim c As Integer = dv.Count.ToString()

asp.net dropdown list postback to anchor

How can I go to an anchor tag on the page when the myDropDownList_SelectedIndexChanged() event fires?
I am using regular ASP.NET Forms.
Update: The following is valid for an ASP.NET Button. I would like to achieve the same functionality (going to #someAnchor) when I select an option from the Dropdown list.
<asp:Button ID="btnSubmit" runat="server" Text="Do IT" Width="186px" PostBackUrl="#myAnchor" CausesValidation="false" />
Update: I will try to further explain details that I didn't cover in enough detail initially.
This is a long page and in the middle of the page there is a dropdown list. Below the dropdown list is a label that will change based on the item selected from the dropdown. The update of the label will occur during the postback. At this point the page needs to remain focused on the dropdown. I tried to use AJAX to accomplish this, but other implementation details prevent that from working. The ability to go to an anchor tag after the postback would be a simple solution. Here is a simplified version of what I am trying to accomplish.
<%# Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub myDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
myLabel.Text = myDropDown.SelectedValue
'When this finishes, go to #myAnchor
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Imagine many lines of text here.
<a name="myAnchor"></a>
<asp:DropDownList ID="myDropDown" runat="server" OnSelectedIndexChanged="myDropDown_SelectedIndexChanged" asdf="asdf" PostBackUrl="#myAnchor"></asp:DropDownList>
<asp:Label ID="myLabel" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
This could do the trick
<asp:DropDownList ID="DropDownList1" runat="server"
onchange="document.location= this.value">
<asp:ListItem Text="Anchor" Value="#anchor"></asp:ListItem>
<asp:ListItem Text="Anchor2" Value="#anchor2"></asp:ListItem>
</asp:DropDownList>
You mention myDropDownList_SelectedIndexChanged() (server code) but you must do it on client side, unless you have a good reason to go to the server
Add this to your page load and you will be good to go.
Page.MaintainScrollPositionOnPostBack = true;
I would use JavaScript--either register the script in your codebehind, or have an asp:Literal which is only visible after the SelectedIndexChanged event. Modify the location.href to append your anchor.
One way to do this is to use the forms.Controls bla bla bla properties in ASP.NET.
however I would suggest you to use a asp.net hyperlink control or link button and this would allow you to access it directly with its ID.
thanks,
MNK.
This requirement has simple javascript solution.But the problem is the design is flawed.Once you move to a new area in screen you cant access the navigation select list without scrolling back.Anyway something like the following works
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Goto(x) {
window.location = "#"+x.value;
}
</script>
</head>
<body>
<select id="Select1" name="D1" onchange="Goto(this);">
<option value="Loc1" >go to 1 </option>
<option value="Loc2">go to 2 </option>
<option value="Loc3">go to 3 </option>
<option value="Loc4">go to 4 </option>
</select><form id="form1" runat="server">
</form>
<strong> <a href="#" id="Loc1" >Location 1</a></strong>
blah
<strong>Location 2</strong>
<strong>Location 3</strong>
<strong>Location 4</strong>
</body>
</html>
Here is what I have implemented to accomplish my desired result.
Protected Sub myDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myDropDown.SelectedIndexChanged
Response.Redirect("Default.aspx?myDropDown=" & myDropDown.SelectedItem.Text.ToString.Trim & "#myAnchor")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim myDropDownValue As String = Request.QueryString("myDropDown")
If myDropDownValue <> "" Then
myDropDown.Items.FindByText(myDropDownValue).Selected = True
Label1.Text = GetTextBasedOnDropDownSelection(myDropDownValue)
End If
End If
End Sub
If your dropdown list contains three items say for example:
Page1
Page2
Page3
Give the dropdownlist a property of AutoPostBack="true" and then in the dropdown OnSelectedIndexChanged method write the following:
if (DDl.SelectedIndex == 1) {
Response.Redirect("~/page1");
}
else if (DDl.SelectedIndex == 2) {
Response.Redirect("~/page2");
}

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?

How to assign a method's output to a textbox value without code behind

How do I assign a method's output to a textbox value without code behind?
<%# Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Public TextFromString As String = "test text test text"
Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w")
Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer)
Return New String(Input, Count)
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=TextFromString%>
<br />
<asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox>
<br />
<%=TextFromMethod%>
<br />
<asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>
</div>
</form>
</body>
</html>
it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me.
It's also confusing to me why
<asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label>
and
<asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox>
works but
<asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox>
causes a compilation error.
There's a couple of different expression types in .ASPX files. There's:
<%= TextFromMethod %>
which simply reserves a literal control, and outputs the text at render time.
and then there's:
<%# TextFromMethod %>
which is a databinding expression, evaluated when the control is DataBound(). There's also expression builders, like:
<%$ ConnectionStrings:Database %>
but that's not really important here....
So, the <%= %> method won't work because it would try to insert a Literal into the .Text property...obviously, not what you want.
The <%# %> method doesn't work because the TextBox isn't DataBound, nor are any of it's parents. If your TextBox was in a Repeater or GridView, then this method would work.
So - what to do? Just call TextBox.DataBind() at some point. Or, if you have more than 1 control, just call Page.DataBind() in your Page_Load.
Private Function Page_Load(sender as Object, e as EventArgs)
If Not IsPostback Then
Me.DataBind()
End If
End Function
Have you tried using an HTML control instead of the server control? Does it also cause a compilation error?
<input type="text" id="TextBox4" runat="server" value="<%=TextFromString%>" />

Resources