How do I stop a databound dropdown list from htmlencoding? - asp.net

ddlCats.DataSource = listOfCats;
ddlCats.DataBind();
If an item contains say, &, it will appear in the ddl as &
How can I stop this? I am using asp.net

im having the same problem here and here is the code for those interested (not a fix but a example of the problem )
<%# Page Language="C#" AutoEventWireup="true" CodeFile="HtmlEncodeDropDownList.aspx.cs" Inherits="ForumExampleCode_HtmlEncodeDropDownList" %>
<!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>HTML Encode Drop Down List Example (english, c# only)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>HTML Encode Drop Down List Example (english, c# only)</h1>
<asp:dropdownlist id="ddlCountry" runat="server" />
<div>
This is how it should look in the drop down list:<br />
côte d'ivoire<br />
são tomé and príncipe
</div>
</div>
</form>
</body>
</html>
and code behind is here
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ForumExampleCode_HtmlEncodeDropDownList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region region 1: create a datatable and fill with values
//note: declare objects
DataTable countryTable = new DataTable();
//note: add data columns to datatabl
DataColumn newColumn1 = new DataColumn();
newColumn1.AllowDBNull = false;
newColumn1.Caption = "three letter ISO country abbreviation";
newColumn1.ColumnName = "iso";
newColumn1.DataType = System.Type.GetType("System.String");
countryTable.Columns.Add(newColumn1);
//note: add data columns to datatable
DataColumn newColumn2 = new DataColumn();
newColumn2.AllowDBNull = false;
newColumn2.Caption = "country name";
newColumn2.ColumnName = "countryName";
newColumn2.DataType = System.Type.GetType("System.String");
countryTable.Columns.Add(newColumn2);
//note: rename table
countryTable.TableName = "CountryList";
//note: add row
DataRow newRow1 = countryTable.NewRow();
newRow1["iso"] = "abc";
newRow1["countryName"] = "côte d'ivoire";
countryTable.Rows.Add(newRow1);
//note: add row
DataRow newRow2 = countryTable.NewRow();
newRow2 = countryTable.NewRow();
newRow2["iso"] = "xyz";
newRow2["countryName"] = "são tomé and príncipe";
countryTable.Rows.Add(newRow2);
#endregion
#region region 2: bind datatable to drop down box
ddlCountry.DataSource = countryTable;
ddlCountry.DataTextField = "countryName";
ddlCountry.DataValueField = "iso";
ddlCountry.DataBind();
#endregion
}
}

Related

ASP.net (VB.Net) Dynamic controls on Pageload and reading their values on button click

I am creating a page with Dynamic controls(Setting ID of controls too) in a table based on a loop in Page Load event.
I need to access the values of those dynamic controls to save in database in button click event. Now, when I loop on the table, it is giving me 0 rows of the table. Secondly, I also try to use the Find_Control Property to find the controls on the page and it is giving me NOTHING for each Control.
Is there something, I am missing, like runat=server? Or there is another approach to access those control on button click event.
ASP.net Code is below
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Table ID="Table1" runat="server">
</asp:Table>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
VB.net is Below (just looping 10 times, Odd rows with text boxes, even rows with Drop down list just as an example)
Option Strict On
Option Explicit On
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If IsPostBack = False Then
Dim li As Integer = 0, lj As Integer = 0
For li = 0 To 9
Dim loR As New TableRow
'-------------------------------
Dim loC1 As New TableCell
loC1.Text = "Caption " & CStr(li + 1).PadLeft(2, CChar("0")) & " :"
loR.Cells.Add(loC1)
'-------------------------------
Dim loC2 As New TableCell
Select Case (li + 1) Mod 2
Case 0
Dim loDD As New DropDownList
loDD.ID = "ctl" & CStr(li + 1).PadLeft(2, CChar("0"))
For lj = 0 To li + 3
loDD.Items.Add("List " & CStr(li + 1).PadLeft(2, CChar("0")) & " : Value " & CStr(lj + 1).PadLeft(2, CChar("0")))
Next
loC2.Controls.Add(loDD)
Case 1
Dim loT As New TextBox
loT.ID = "ctl" & CStr(li + 1).PadLeft(2, CChar("0"))
loC2.Controls.Add(loT)
End Select
loR.Cells.Add(loC2)
'-------------------------------
Table1.Rows.Add(loR)
Next
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim li As Integer = 0
For li = 0 To Table1.Rows.Count - 1
Response.Write("")
Next
End Sub
End Class
Hi for storing and retrieving values from the dynamically created control we need to follow 3 steps,
1) create dynamic controls as per our need
2) override viewstate's two methods that is LoadViewState and SaveViewState as per below my code snippet
protected void CreateDynamicTextBox()
{
Label lableVendorName = new Label();
lableVendorName.Text = "Vendor Name";
TextBox VendorName = new TextBox();
VendorName.ID = "VendorName";
PanelVendor.Controls.Add(lableVendorName);
PanelVendor.Controls.Add(VendorName);
}
protected override void LoadViewState(object savedState)
{
//if we can identify the custom view state as defined in the override for SaveViewState
if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])
{
object[] newViewState = (object[])savedState;
string[] txtValues = (string[])(newViewState[0]);
if (txtValues.Length > 0)
{
CreateDynamicTextBox();
(PanelVendor.FindControl("VendorName") as TextBox).Text = txtValues[0];
}
//load the ViewState normally
base.LoadViewState(newViewState[1]);
}
else
{
base.LoadViewState(savedState);
}
}
protected override object SaveViewState()
{
object[] newViewState = new object[2];
List<string> txtValues = new List<string>();
if (PanelVendor.Controls.Count > 1)
{
txtValues.Add((PanelVendor.FindControl("VendorName") as TextBox).Text);
}
newViewState[0] = txtValues.ToArray();
newViewState[1] = base.SaveViewState();
return newViewState;
}
and now retrieve the value from that control as below
protected void btnItem_Click(object sender, EventArgs e)
{
string VendorName = (PanelVendor.FindControl("VendorName") as TextBox).Text;
}
hope this would help. happy coding :)

set mintime and maxtime of timefield dynamically in ext.net

I am working with EXT.NET 1.2
I want to set minTime and maxTime from codebehind(from cs Page).
I ha dwritten following code but not working that code.. is their any mistake or is ther any another method(through Javascript)??
Code
tmFrom.Increment = 30;
string strmin = obj.startTime.ToShortTimeString();
DateTime dtmin = DateTime.ParseExact(strmin, "H:mm tt", CultureInfo.InvariantCulture);
string strmax = obj.endTime.ToShortTimeString();
DateTime dtmax = DateTime.ParseExact(strmax, "H:mm tt", CultureInfo.InvariantCulture);
tmFrom.Format = "H:mm";
tmFrom.MinTime = dtmin.TimeOfDay;
tmFrom.MaxTime = dtmax.TimeOfDay;
I am setting minTime and maxTime from Database value.
Based on your code sample, it appears obj.startTime and obj.endTime are both already DateTime objects. You should not have to convert into Strings, then back into DateTime objects.
The following sample demonstrates the complete scenario.
Example
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
var startTime = DateTime.Now.AddMinutes(-215);
var endTime = DateTime.Now.AddMinutes(215);
var time = this.TimeField1;
time.Increment = 30;
time.Format = "H:mm";
time.MinTime = startTime.TimeOfDay;
time.MaxTime = endTime.TimeOfDay;
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET Examples</title>
</head>
<body>
<ext:ResourceManager runat="server" />
<ext:TimeField ID="TimeField1" runat="server" FieldLabel="Time" />
</body>
</html>
Hope this helps

What control to use to display main & sub tables

ASP.NET 3.5 & SQL 2008
I have this main table & a subtable. For each set of calculation, 1 record is added to the main table & several records to the subtotal.
Most of user entered data goes into the subtable & some into the main table.
Currently I have a web page set up with several textboxes to get the data from the user & the resulting calculations are displayed in a gridview.
The gridview shows all the records from the Main table.
Each time the user selects a record from the gridview, I want to invoke another page where the user can change the data for the selected record.
It will be nice if I can display the 1 record from the main tablle & all the related records form the subtable.I don't want to use free floating textboxes.
What controls will be the easiest to use for such an application?
you can use grid view in two pages it self...
Here you have to use session variables to store the value of gridview rows in first page then retrieve the session value and display the row in gridview control in the second page.
If you use gridview control to display the data which get from database in the first page ,as far as I know you can also just pass the unique value of record(such as id) to an other page ,then use the unique value as a condition to search the record in database and display the record by using gridview control in the second page.
Sample:
1.Code in the first page(.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>PassValue</HeaderTemplate>
<ItemTemplate>
Pass
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
2.Code in the first page(.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
public void Bind()
{
this.GridView1.DataSource = Get_source();
this.GridView1.DataBind();
}
// You can get the datatbale form your own database.
// I get the datasource like this in order to run the sample convenient.
public DataTable Get_source()
{
DataTable dt = new DataTable();
DataRow dr;
string XM = "true,false,false,true";
string XMM = "1,2,3,4";
string[] list1 = XM.Split(',');
string[] list2 = XMM.Split(',');
dt.Columns.Add(new DataColumn("ActiveStatus"));
dt.Columns.Add(new DataColumn("number"));
for (int i = 0; i < list1.Length; i++)
{
dr = dt.NewRow();
dr["ActiveStatus"] = list1[i];
dr["number"] = list2[i];
dt.Rows.Add(dr);
}
return dt;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i = e.Row.RowIndex;
Session["row"+i] = e.Row;
}
3.Code in the second page(which named as OtherPage.aspx)
OtherPage.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
4.Code in the second page(.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
string i = Request.QueryString["id"].ToString();
if (Session["row"+i] != null)
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
GridViewRow row = (GridViewRow)Session["row" + i];
for (int xm = 0; xm < row.Cells.Count; xm++)
{
dt.Columns.Add(new DataColumn());
dr[xm] = row.Cells[xm].Text;
}
dt.Rows.Add(dr);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
}
if you want to modify the data in second page, you can modify ... I hope it will helps you...

Why can't the attribute imageurl in the image tag not accept an absolute path?

I'm using two image tags. In one the used path is relative and in the other it is absolute. The absolute path image is not shown. Here is the code:
Expt_Image2.aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Expt_Image2.aspx.cs" Inherits="Expt_Image2" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image
ID="Image1"
runat="server"
ImageUrl="~/Image/Bluehills.jpg"
Height="100"
Width="100"/>
<asp:Image
ID="Image2"
runat="server"
ImageUrl="C:\Documents and Settings\Lovey\My Documents\Visual Studio 2008\WebSites\Expt-New\Image\Sunset.jpg"
Height="100"
Width="100"/>
</div>
</form>
</body>
</html>
Expt_Image2.aspx.cs:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
public partial class Expt_Image2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles(MapPath("~/Image/"));
Image im = new Image();
im.ImageUrl = files[1];
im.AlternateText = files[1];
form1.Controls.Add(im);
}
}
The first error that in your Page_Load method you get your image and store it in array. In C# indexes of items in arrays start from 0, not from 1.
Second, you must specify the virtual path to the property ImageUrl of the Image control.
It is the right Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles( MapPath( "~/Image/" ) );
Image im = new Image();
im.ImageUrl = "~/Image/" + Path.GetFileName( files[ 0 ] );
im.AlternateText = files[ 0 ];
im.Height = 100;
im.Width = 100;
form1.Controls.Add( im );
}
Doesn't MapPath return the physical location of the file. In your case something like C:\inetpub\wwwroot\mysite\image
Whereas you would want the virtual path eg. http://mysite/image/image1.png
Something like this should work:
DirectoryInfo di = new DirectoryInfo(MapPath("~/Image/"));
FileInfo[] files = di.GetFiles();
Image im = new Image();
im.ImageUrl = "~/Image/" + files[0].Name;
im.AlternateText = "~/Image/" + files[0].Name;
form1.Controls.Add(im);
Use the application path,
Request.ApplicationPath + "~/Image/"
This will fix the problem.
One more thing. You don't need to put "~" before the path.

Setting the src attribute of an IFrame to data:application/pdf;base64?

Setting the src attribute of an IFrame to data:application/pdf;base64, isn't working for me, any ideas why?
Here's the .aspx markup
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function loadIFrameFromHiddenField()
{
//get the node containing the base64 pdf data from the xml in the hidden field
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(document.getElementById("pdfData").value);
xmlDoc.setProperty('SelectionLanguage', 'XPath');
var pdfDataNode = xmlDoc.selectSingleNode("//PDF");
//if we've got the node
if (pdfDataNode != null)
{
//get the data and append it to the src contents
var pdfIFrameSrc = "data:application/pdf;base64," + pdfDataNode.text;
//set the src attribute
document.getElementById("pdfIFrame").setAttribute("src", pdfIFrameSrc);
}
}
</script>
</head>
<body>
<form id="form1" runat="server" style="width:100%;height:100%;">
<asp:HiddenField ID="pdfData" runat="server" />
<div style="width:100%;height:80%;">
<iframe id="pdfIFrame" runat="server" scrolling="auto" frameborder="0" marginheight="0" marginwidth="0" style="height:99.5%;width:99.5%" />
</div>
</form>
</body>
</html>
and here's the code behind:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//get the bytes from our PDF
Byte[] pdfBytes = File.ReadAllBytes("c:\\temp\\Test.pdf");
//build xml containiing our base64 encoded pdf data and put it in hidden field
pdfData.Value = buildDocumentXML(pdfBytes, "TestDoc");
//call js function to add the src to the iframe
String scriptText = "<script type='text/javascript'>loadIFrameFromHiddenField()</script>";
ClientScript.RegisterStartupScript(this.GetType(), "loadIFrameFromHiddenField", scriptText);
}
private string buildDocumentXML(Byte[] pdfBytes, string documentName)
{
StringBuilder documentsString = new StringBuilder();
XmlWriterSettings documentsXmlSettings = new XmlWriterSettings();
documentsXmlSettings.Indent = false;
documentsXmlSettings.OmitXmlDeclaration = true;
documentsXmlSettings.ConformanceLevel = ConformanceLevel.Fragment;
documentsXmlSettings.NewLineHandling = NewLineHandling.None;
using (XmlWriter documentsXmlWriter = XmlWriter.Create(documentsString, documentsXmlSettings))
{
documentsXmlWriter.WriteStartElement("DOCUMENTS");
documentsXmlWriter.WriteStartElement("FILENAME");
documentsXmlWriter.WriteString(documentName);
documentsXmlWriter.WriteEndElement();
documentsXmlWriter.WriteStartElement("PDF");
documentsXmlWriter.WriteBase64(pdfBytes, 0, pdfBytes.Length);
documentsXmlWriter.WriteEndElement();
documentsXmlWriter.WriteEndElement();
}
return documentsString.ToString();
}
}
I should say unlike in this example, in the real app, the pdf data is generated serverside. The reason I'm trying to load the pdf data clientside is I have to have the pdf byte data clientside anyway to do something else with and I'm trying to reduce instances of this data being generated and chucked around.
Just stick the above code and markup into a simple one page website in VS2005 and stick any old pdf in c:\temp\, call it TestDoc.pdf and it should compile and run.
Basically the behaviour I'm getting is nothing in the iframe at all.
I'm using IE7 so that might be a problem. I don't know since there's precious little information about using the data:application/pdf;base64[base64 data] syntax around.
It may be tacky to reference wikipedia, but Wikipdia says that there may be some restrictions on which filestypes you are allowed to use the data:filetype;base64 syntax on. Namely, only pictures for now. The IE9 spec, the article says, allows for broader use, but I'm not sure what exactly that entails. In the meantime, you'll just have to use the .pdf file and not just it's base 64 string data.
this way worked for me :
var oldsrc = $('.content-control-iframe').attr('src');
var newsrc = $('.content-control-iframe').attr('src').slice(8);
$('.content-control-iframe[src="'+oldsrc+'"]').attr('src', newsrc);
As far as I know, IE doesn't handle the data: URL scheme at all, so I guess, it doesn't know what to pass to the PDF viewer. See WP.
Cheers,

Resources