I have a multiline textbox, txtPostContest and several buttons that can be clicked to add an HTML tag to the text box (it's for people who won't know any HTML themselves).
However, the buttons only add text once, and after one is clicked none of the others will add text either.
HTML
<div>
<label>Post Content:</label>
</div>
<div>
<asp:Button ID="btnBold" runat="server" Text="Bold" Width="90px" />
<asp:Button ID="btnItal" runat="server" Text="Italics" Width="90px" />
<asp:Button ID="btnLink" runat="server" Text="Link" Width="90px" />
<asp:Button ID="btnImage" runat="server" Text="Image" Width="90px" />
</div>
<div>
<asp:TextBox id="txtPostContent" runat="server" Width="600px" Height="400px" TextMode="MultiLine" />
</div>
VB.Net
Partial Class blogmanager
Inherits System.Web.UI.Page
Dim bold As String = " <strong> </strong> "
Dim ital As String = " <em> </em> "
Dim img As String = " <img src="PASTE IMAGE FILE HERE" alt="TYPE ALTERNATE TEXT HERE" height="250" width="300"> "
Dim link As String = "<a href="PASTE HYPERLINK HERE">PASTE LINK TEXT HERE</a>"
Protected Sub btnBold_Click(sender As Object, e As System.EventArgs) Handles btnBold.Click
txtPostContent.Text += bold
End Sub
Protected Sub btnItal_Click(sender As Object, e As System.EventArgs) Handles btnItal.Click
txtPostContent.Text += ital
End Sub
Protected Sub btnLink_Click(sender As Object, e As System.EventArgs) Handles btnLink.Click
txtPostContent.Text += link
txtPostContent.Text = txtPostContent.Text.Replace(""", ControlChars.Quote)
End Sub
Protected Sub btnImage_Click(sender As Object, e As System.EventArgs) Handles btnImage.Click
txtPostContent.Text += img
txtPostContent.Text = txtPostContent.Text.Replace(""", ControlChars.Quote)
End Sub
I can't see the problem in the simple text += string method but obviously it's no good. Is there a more effective way to bung some text into an existing textbox?
If you click any button such as Bold first, it would work and display
.
But any other click would result an error. For instance when you click italics button
A potentially dangerous Request.Form value was detected from the client (txtPostContent=" ").
The culprit is the text you set in the textarea (). It's potentially dangerous text.
You may want to google for the cross site scripting for details.
Once you put HttpUtility.HtmlEncode function call on all text, the error would be gone. For instance
txtPostContent.Text += HttpUtility.HtmlEncode(bold)
You can add tag validateRequest="false" in your <%# page. but this is highly NOT recommended!!!
Related
the text box accepts multiple 0 when the first digit is already a 0
<asp:TemplateColumn>
<HeaderTemplate>
Consumed
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="txtConsumed" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvtxtQty" runat="server"
ControlToValidate="txtConsumed" Display="Dynamic" ErrorMessage="*Required"
ValidationGroup="Val_Packages" />
<ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender27" runat="server" TargetControlID="txtConsumed"
FilterType="Numbers" Enabled="True" />
<br />
</ItemTemplate>
</asp:TemplateColumn>
I need textbox to show only 1 "0" when I press 0 many times.
You could use the following code. The KeyPress event triggers code that will not allow any non-digit characters and the KeyUp event triggers code that removes all but one leading zero. It will work while you input the text as you requested.
Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp
If Mid(TextBox1.Text, 1, 1) = "0" Then
If Mid(TextBox1.Text, 2, 1) = "0" Then
TextBox1.Text = Mid(TextBox1.Text, 2, Len(TextBox1.Text) - 1)
Else
End If
Else
End If
TextBox1.SelectionStart = Len(TextBox1.Text) + 1
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar))
End Sub
Ive use a regexvalidator. Here is the link to try it.
https://regex101.com/r/wV9mD8/23
Hi Below is the code for Uploading Multiple files I cant display all the file names at a time it shows only one file name and how to create hyperlink to Uploaded documents to view the files.
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
If FileUpload1.HasFile Then
Try
FileUpload1.SaveAs("Destinationpath\testing\\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.FileName & "<br>"
ListBox1.Items.Add(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName))
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
'Files.RemoveAt(ListBox1.SelectedIndex)
ListBox1.Items.Remove(ListBox1.SelectedItem.Text)
Label1.Text = "File removed"
End Sub
and below is the aspx code
<div>
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true"/><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Upload Document" /><br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label></div>
<asp:listbox ID="ListBox1" runat="server" Width="175px"></asp:listbox>
<asp:Button ID="Button2" runat="server" Text="Remove" Width="98px" OnClick="Button2_Click" />
can anyone help me to do this. Thanks..
Use ListBox for this. It will be something like:
protected void UploadButton_Click(object sender, EventArgs e){
foreach (HttpPostedFile fl in fu.PostedFiles)
{
fl.SaveAs(DestinationPath + fl.FileName);
ListItem li = new ListItem();
li.Text = fl.FileName;
ListBox1.Items.Add(li);
}
}
In your design page:
<asp:Panel ID="pnlFiles" runat="server" />
Your code behind:
Protected Sub Button1_Click(ByVal sender As Object, _ByVal e As System.EventArgs)
For Each fl as HttpPostedFile in fu.PostedFiles
Dim fileLink as String = DestinationPath + fl.FileName
fl.SaveAs(fileLink)
Dim hpr as New HyperLink
hpr.Text = "Download file"
hpr.NavigateUrl = fileLink
pnlFiles.Controls.Add(hpr)
Next
End Sub
I have problem with onclick event. Here is an example which is similar to my project
HTML
<%# Page Language="VB" AutoEventWireup="true" CodeFile="Example.aspx.vb" Inherits="Example" %>
<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
<asp:Label ID="label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
VB
Partial Class Example
Inherits System.Web.UI.Page
Dim No_of_Animals As Integer = 6 ' Number of Animals
Dim Cage(No_of_Animals) As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
label1.Text = " Animal released: " & Session.Item("AnimalReleased")
Cage(0) = "Cow"
Cage(1) = "Bat"
Cage(2) = "Dog"
Cage(3) = "Cat"
Cage(4) = "Snake"
Cage(5) = "Pig"
Dim html As New StringBuilder()
html.Append("<table>")
For Animal = 1 To No_of_Animals
html.Append("<tr><td>Cage " & Animal & " : </td>")
html.Append("<td> " & Cage(Animal - 1) & "</td>")
html.Append("<td><button runat=""server"" OnServerClick=""DisplayAnimal(" & Animal - 1 & ")"">Release</button></td></tr>")
Next
html.Append("</table>")
PlaceHolder1.Controls.Add(New Literal() With {.Text = html.ToString()})
End Sub
Public Sub DisplayAnimal(ByVal CageNo As Integer)
Session.Item("AnimalReleased") = Cage(CageNo)
End Sub
End Class
After I click a button the page will just refresh but session.item("AnimalRelease") was never given a value.
I'm suspecting onclick is not functioning well.
According to MSDN, the OnServerClick should be all lower case: "onserverclick".
I need help with getting the ID of the Control in RadGrid in order to set it Visable=False.
The last function is actually creating a pic based on the value that's coming from the DB. How can I set the HyperLink next to the Pic that I'm adding to Visible false?
I think that I need to send that function RenderLinked the hyperlink control but I don't know how and I hope that some one can show me the way.
<telerik:RadGrid
ID="rgPhoneBook"
runat="server"
AutoGenerateColumns="False"
AllowPaging="True"
AllowSorting="True"
PageSize="50"
CellSpacing="0" GridLines="None"
OnItemCommand="rgPhoneBook_ItemCommand"
OnPageIndexChanged="rgPhoneBook_OnPageIndexChanged"
OnSortCommand="rgPhoneBook_OnSortCommand"
OnItemCreated="rgPhoneBook_OnItemCreated"
EnableHeaderContextFilterMenu="True"
Width="933px"
Height="528px">
<ClientSettings>
<Selecting AllowRowSelect="True"></Selecting>
<Scrolling AllowScroll="true" UseStaticHeaders="True" SaveScrollPosition="true" FrozenColumnsCount="2" />
</ClientSettings>
<MasterTableView ShowHeadersWhenNoRecords="true" NoMasterRecordsText="No PhoneBook Records to display" Font-Size="11px" GridLines="None" AllowPaging="True" ItemStyle-Height="25px" CommandItemDisplay="Top" AllowAutomaticUpdates="False" TableLayout="Auto" DataKeyNames="LocationID,PersonID" ClientDataKeyNames="LocationID,PersonID">
<PagerStyle Mode="NumericPages"></PagerStyle>
<Columns>
<telerik:GridTemplateColumn HeaderText="Linked" HeaderStyle-Width="45px" >
<ItemTemplate>
<span id="spanHyperLink" style="visibility:visible" runat="server">
<asp:HyperLink ID="Link" runat="server" Text="Link">
</asp:HyperLink>
</span>
<%# RenderLinked(DataBinder.Eval(Container.DataItem, "Linked"))%>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Protected Function RenderLinked(ByVal inputVal As String) As String
Dim output As String = ""
Try
Dim svcs As New SystemServices
If Not inputVal Is Nothing And Not String.IsNullOrEmpty(inputVal) Then
If inputVal = True Then
output = "<img src='" + Globals.gRootRelativeSecureURL("\Images\Layout\Link.png") + "' width=""13"" height=""13"" border=""0"" align=""absmiddle"">"
Else
'Dim item As GridDataItem = DirectCast(e.Item, GridDataItem)
'Dim link As HyperLink = DirectCast(item("Link").Controls(0), HyperLink)
'LinkButton.DisabledCssClass = True
Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "StartupScript", "Sys.Application.add_load(function() { DisableHyperLinkCSS(); });", True)
'output = "<a herf='#' onclick='showPersonLinkModal() ;'>Link</a>"
End If
End If
Catch ex As Exception
Globals.SendEmailError(ex, m_User.SessionID, System.Reflection.MethodBase.GetCurrentMethod.Name.ToString(), Request.RawUrl.ToString(), m_User.UserID)
End Try
Return output
End Function
If you want to set some control's attribute visible=false in code behind when rows are bound to data 1 by 1 you may use RowDataBound event and write following code in it's handler
Control_Type Control_ID = (Control_Type) e.Row.FindControl("Control_ID");
Control_ID.Visible = false;
And if you want to set it in javascript,
rgPhoneBook.Rows[Record_Index].Cells[0].Visible = false;
Hope this helps you. The above code is in C#, please convert it to it's equivalent in VB.
I have a bit of a difficult problem which I can't seem to find out how to solve.
Basically, I have a couple tables on my database which, identify, by client, which divs IDs the client has access to, by using the tab
So I have a table which identifies the divs by their ID, by using the table index:
id | id_div
0 | D0
1 | D1
(and so on..)
And then another one which has only the clients ID and the divs (identified by the "id" field) he has access to:
client_id | div_id
29 | 0
29 | 1
(and so on..)
Then I'm cross referencing which divs should be visible and which should not.
The problem is I am getting the divs id as a string and in order to be able to tell in code-behind to set the visibility to false I need to reference the div in itself..
A sample:
<dx:TabPage Name="tabServico" Text="<%$ Resources:InterfaceGenerica, lblServico %>">
<ContentCollection>
<dx:ContentControl>
<div class="conteudo_pagina_tab">
<asp:HiddenField ID="hidID" runat="server" Value="0" EnableViewState="true" />
<asp:HiddenField ID="hidIdCliente" runat="server" Value="0" EnableViewState="true"/>
<div id="D0" runat="server">
<div class="cols coluna1">
<asp:Literal ID="litClientes" runat="server" Text="<%$ Resources:InterfaceGenerica, lblCliente %>"></asp:Literal>
</div>
<div class="cols coluna2-4">
<dx:ASPxComboBox ID="cboClientes" runat="server" HelpText="" ValueField="id_cliente" TextField="nome_completo" SelectedValue="" Width="100%" AutoPostBack="true"></dx:ASPxComboBox>
</div>
</div>
<clear></clear>
<div id="D1" runat="server">
<div class="cols coluna1">
<asp:Literal ID="litTipoOperacao" runat="server" Text="<%$ Resources:InterfaceGenerica, lblOperacao %>"></asp:Literal>
</div>
<div class="cols coluna2-4">
<dx:ASPxComboBox ID="cboTipoOperacao" runat="server" Width="100%" HelpText="" ValueField="id_operacoes" TextField="nome" SelectedValue="" AutoPostBack="true">
</dx:ASPxComboBox>
</div>
</div>
<clear></clear>
<div id="D2" runat="server">
<div class="cols coluna1">
<asp:Literal ID="litTipoServs" runat="server" Text="<%$ Resources:InterfaceGenerica, lblTipoServico %>"></asp:Literal>
</div>
<div class="cols coluna2-4">
<dx:ASPxComboBox ID="cboTipoServs" runat="server" HelpText="" ValueField="id_tipo_servs" TextField="nome" SelectedValue="" AutoPostBack="true" Width="100%"></dx:ASPxComboBox>
</div>
</div>
<div id="D3" runat="server">
<div class="cols coluna5">
<asp:Literal ID="litSubTipoServs" runat="server" Text="<%$ Resources:InterfaceGenerica, lblSubtipoServico %>"></asp:Literal>
</div>
<div class="cols coluna6-8">
<dx:ASPxComboBox ID="cboSubTipoServs" runat="server" HelpText="" ValueField="id_tipo_subtipos" TextField="nome" SelectedValue=""></dx:ASPxComboBox>
</div>
</div>
And in code behind I have:
Dim cross As New Hashtable()
Dim divsCliente() As String
Dim lstDivs As List(Of campos_agd_form)
lstDivs = campos_agd_form_mapper.CarregarDivs()
If lstDivs IsNot Nothing Then
For Each i In lstDivs
cross.Add(i.id, i.id_div)
Next
End If
Dim lstDivsCliente As List(Of clientes_campos_agd)
lstDivsCliente = clientes_campos_agd_mapper.CarregarCamposCliente(guser.id)
If lstDivsCliente IsNot Nothing Then
divsCliente = (lstDivsCliente.Item(0).id_campos_enum).Split(",")
End If
'Dim divsCliente() As Integer = Convert.ToInt32((lstDivsCliente.id_divs).Split(","))
For Each item In cross
For Each i In divsCliente
If item.Key = Convert.ToInt32(i) Then
Dim div As System.Web.UI.HtmlControls.HtmlGenericControl
div = TryCast(item.Value, System.Web.UI.HtmlControls.HtmlGenericControl)
div.Visible = False
End If
Next
Next
As I was already expecting I can't convert a string into a HtmlObject so what I need to do is to find an object by it's id (the string), without having to go through the parent-object (basically, search the whole document, like one would do with javascript with a getElementById)
How can this be accomplished?
The framework I'm using is .NET 4.0
I Recommend the following approach.
You need to know which information to show to each user, so you might want to store this in session for example (Global.asax):
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fetch from DB
Session("Rights") = {"MyID1", "MyID3"}
End Sub
Then create a base user control that checks from the session if it's id is in the list of the rights the user has. If not, the control will automatically hide it self:
Imports System.Linq
Public MustInherit Class MyBaseControl
Inherits System.Web.UI.UserControl
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If Page.IsPostBack Then Return
Dim rights As String() = CType(Session("Rights"), String())
If Not rights.Any((Function(s) s = Me.ID)) Then Me.Visible = False
End Sub
End Class
Then create x number of content controls that inherit from this base control. These controls can have totally different content, but consider making as few as possible, since your D0, D1 etc seem to have almost same content. So just customize the control to handle different texts and values:
Public Class MyControl1
Inherits MyBaseControl
End Class
Then on the page you will have as many of these controls as needed:
<div>
<uc1:MyControl1 ID="MyID1" runat="server" />
<uc2:MyControl2 ID="MyID2" runat="server" />
<uc3:MyControl3 ID="MyID3" runat="server" />
</div>
Hope this helps.
So, I ended up doing things a little differently.
Basically I'm using a ClientScriptManager, and constructing an array with the elements to hide. (Which is then passed to the client side).
So the function now looks like this:
Private Sub ManipulaFormCliente()
Dim cross As New Hashtable()
Dim divsCliente() As String = New String() {}
Dim aux() As String = New String() {}
Dim cs As ClientScriptManager = Page.ClientScript
Dim lstDivs As List(Of campos_agd_form)
lstDivs = campos_agd_form_mapper.CarregarDivs()
If lstDivs IsNot Nothing Then
For Each i In lstDivs
cross.Add(i.id, i.id_div)
Next
End If
Dim lstDivsCliente As List(Of clientes_campos_agd)
lstDivsCliente = clientes_campos_agd_mapper.CarregarCamposCliente(" id_cliente = " & Convert.ToInt32(hidIdCliente.Value))
If lstDivsCliente IsNot Nothing Then
If lstDivsCliente.Count <> 0 Then
divsCliente = (lstDivsCliente.Item(0).id_campos_enum).Split(",")
End If
End If
For Each item In cross
For Each i In divsCliente
If item.Key = Convert.ToInt32(i) Then
cs.RegisterArrayDeclaration("divsCliente", "'" & item.Value & "'")
End If
Next
Next
End Sub
Then, on the client side I made a function which runs once the window has loaded, and uses the array constructed on code-behind to apply a css "display: none" on the divs whose IDs get passed on the array.
The code is the following:
window.onload = function hideFields() {
if (divsCliente.length > 0) {
for (var i = 0; i < divsCliente.length; i++) {
document.getElementById(divsCliente[i]).style.display = 'none';
}
}
}
This implements the behaviour desired: Whenever there's a postback (and respective load) this function is run, hiding the required divs/fields.
As a final touch, I had to add the 'clientidmode = "static"' attribute to the divs, in order to get the getElementById() function to work properly (according to the data in the DB)
I hope this helps anyone in need of a similar solution.