Some time back on the form somebody was looking for some help in searching URL within text and make those URLs as link. Me and that guy tried various regex but the one that worked out I thought to put it on the blog so that it can help me and others later. Regex itself is:
-------- In VB.Net ---------
Dim regx As New Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase)
-------- In C#.Net ---------
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
And I used following method to convert the URLs into link within text.
-------- In VB.Net ---------
Protected Function MakeLink(ByVal txt As String) As String
Dim regx As New Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase)
Dim mactches As MatchCollection = regx.Matches(txt)
For Each match As Match In mactches
txt = txt.Replace(match.Value, "<a href='" & match.Value & "'>" & match.Value & "</a>")
Next
Return txt
End Function
------- In C#.Net --------
protected string MakeLink(string txt)
{
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(txt);
foreach (Match match in mactches) {
txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
}
return txt;
}
Since long I was wondering on how I will be able to use FileUpload control inside UpdatePanel and I am sure there will be lot of other people who were expecting the same to be working. I found an intersting video article by Joe Stagner in which he described how to use the FileUpload control inside iframe to give some AJAX effect. You can find this video here. http://www.asp.net/learn/videos/video-254.aspx
I response to one of my blog post entry I received few queries regarding mutually exclusive checkbox within GirdView, meaning if there are two checkboxes in a row only one can be selected at a time. If checkbox1 is selected and you select checkbox2 then checkbox1 should be deselected. Following javascript and html can be used.
<script type="text/javascript">
function checkMutuallyExclusive(target)
{
document.getElementById(target).checked = false;
}
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="cbStatus1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbStatus1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
AlternatingItemTemplate>
<asp:CheckBox ID="cbStatus2" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbStatus2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
----------------------------------.vb file if VB.Net is the language ------------------------------------
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
DirectCast(e.Row.FindControl("cbStatus1"), CheckBox).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" & DirectCast(e.Row.FindControl("cbStatus2"), CheckBox).ClientID & "')")
DirectCast(e.Row.FindControl("cbStatus2"), CheckBox).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" & DirectCast(e.Row.FindControl("cbStatus1"), CheckBox).ClientID & "')")
End If
End Sub
----------------------------------.cs file if C#.Net is the language ------------------------------------
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow)) {
((CheckBox)e.Row.FindControl("cbStatus1")).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" + ((CheckBox)e.Row.FindControl("cbStatus2")).ClientID + "')");
((CheckBox)e.Row.FindControl("cbStatus2")).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" + ((CheckBox)e.Row.FindControl("cbStatus1")).ClientID + "')");
}
}
Different forums are filled with the questions regarding how to manually implement cookies for login or in other words how to implement "Remeber me" option.
Following is the code that will give the idea of how to achieve this task.
Controls used
1. TextBox, ID = TbUserName
2. TextBox, ID = TbPassword
3. CheckBox, ID = CbRememberMe
4. Button, ID = BtLogin
5. LinkButton, ID = lbSignout
------------------If you are using VB.Net-------------------------
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'Check if the browser support cookies
If Request.Browser.Cookies Then
'Check if the cookies with name PBLOGIN exist on user's machine
If Request.Cookies("PBLOGIN") IsNot Nothing Then
'Pass the user name and password to the VerifyLogin method
Me.VerifyLogin(Request.Cookies("PBLOGIN")("UNAME").ToString(), Request.Cookies("PBLOGIN")("UPASS").ToString())
End If
End If
End If
End Sub
Protected Sub BtLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'check if remember me checkbox is checked on login
If (Me.CbRememberMe.Checked) Then
'Check if the browser support cookies
If (Request.Browser.Cookies) Then
'Check if the cookie with name PBLOGIN exist on user's machine
If (Request.Cookies("PBLOGIN") Is Nothing) Then
'Create a cookie with expiry of 30 days
Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(30)
'Write username to the cookie
Response.Cookies("PBLOGIN").Item("UNAME") = Me.TbUserName.Text
'Write password to the cookie
Response.Cookies("PBLOGIN").Item("UPASS") = Me.TbPassword.Text
'If the cookie already exist then wirte the user name and password on the cookie
Else
Response.Cookies("PBLOGIN").Item("UNAME") = Me.TbUserName.Text
Response.Cookies("PBLOGIN").Item("UPASS") = Me.TbPassword.Text
End If
End If
End If
Me.VerifyLogin(Me.TbUserName.Text, Me.TbPassword.Text)
End Sub
Protected Sub VerifyLogin(ByVal UserName As String, ByVal Password As String)
Try
'If login credentials are correct
'Redirect to the user page
'else
'prompt user for invalid password
'end if
Catch ex as System.Exception
Response.Write(ex.Message)
End Try
End Sub
Protected Sub lbSignout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbSignout.Click
'Check iIf the cookies with name PBLOGIN exist on user's machine
If (Request.Cookies("PBLOGIN") IsNot Nothing) Then
'Expire the cookie
Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(-30)
End If
'Redirect to the login page
End Sub
End Class
------------------If you are using C#.Net-------------------------
partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
//Check if the browser support cookies
if (Request.Browser.Cookies)
{
//Check if the cookies with name PBLOGIN exist on user's machine
if (Request.Cookies("PBLOGIN") != null)
{
//Pass the user name and password to the VerifyLogin method
this.VerifyLogin(Request.Cookies("PBLOGIN")("UNAME").ToString(), Request.Cookies("PBLOGIN")("UPASS").ToString());
}
}
}
}
protected void BtLogin_Click(object sender, System.EventArgs e)
{
//check if remember me checkbox is checked on login
if ((this.CbRememberMe.Checked))
{
//Check if the browser support cookies
if ((Request.Browser.Cookies))
{
//Check if the cookie with name PBLOGIN exist on user's machine
if ((Request.Cookies("PBLOGIN") == null))
{
//Create a cookie with expiry of 30 days
Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(30);
//Write username to the cookie
Response.Cookies("PBLOGIN").Item("UNAME") = this.TbUserName.Text;
//Write password to the cookie
Response.Cookies("PBLOGIN").Item("UPASS") = this.TbPassword.Text;
}
//If the cookie already exist then wirte the user name and password on the cookie
else
{
Response.Cookies("PBLOGIN").Item("UNAME") = this.TbUserName.Text;
Response.Cookies("PBLOGIN").Item("UPASS") = this.TbPassword.Text;
}
}
}
this.VerifyLogin(this.TbUserName.Text, this.TbPassword.Text);
}
protected void VerifyLogin(string UserName, string Password)
{
try
{
//If login credentials are correct
//Redirect to the user page
//else
//prompt user for invalid password
//end if
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
protected void lbSignout_Click(object sender, System.EventArgs e)
{
//Check iIf the cookies with name PBLOGIN exist on user's machine
if ((Request.Cookies("PBLOGIN") != null))
{
//Expire the cookie
Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(-30);
}
//Redirect to the login page
}
}
If you want to add an option that users can click a button on your website and it will open up bookmark option. Following is the code that will perform this task.
<html>
<body>
<SCRIPT LANGUAGE="JavaScript">
function bookmark(url, description)
{
if (navigator.appName=='Microsoft Internet Explorer')
{
window.external.AddFavorite(url, description);
}
else
{
alert('This option works with IE only as of now.');
}
}
</SCRIPT>
<input type="Button" ID="btnBookMark" onClick="bookmark('http://mypage.aspx','MyWebsite')" value="Bookmark" />
</body>
</html>
If you come up with some requirement in which you have a Checkbox and a DropDownList in GridView control and you are requried to enable disable the DropDownList on the basis of the CheckBox value you can use following Code.
-----------------------------------.aspx file ----------------------------------
<script type="text/javascript">
function StatusGridDropdown(drpdown)
{
document.getElementById(drpdown).disabled = !document.getElementById(drpdown).disabled;
}
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="cbStatus" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:DropDownList ID="ddl" runat="server" Enabled="False" Width="169px">
</asp:DropDownList>
</AlternatingItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddl" runat="server" Width="169px" Enabled="False">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
----------------------------------.vb file if VB.Net is the language ------------------------------------
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
DirectCast(e.Row.FindControl("cbStatus"), CheckBox).Attributes.Add("onclick", "javascript:StatusGridDropdown('" & DirectCast(e.Row.FindControl("ddl"), DropDownList).ClientID & "')")
End If
End Sub
----------------------------------.cs file if C#.Net is the language ------------------------------------
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow)) {
((CheckBox)e.Row.FindControl("cbStatus")).Attributes.Add("onclick", "javascript:StatusGridDropdown('" + ((DropDownList)e.Row.FindControl("ddl")).ClientID + "')");
}
}
I was replying to one of the post on the ASP.Net forum in which the requirement was like reading txt file contents from different webservers. When he got satisfied with the solution then I thought to put the piece of code in my blog as well for others and my future reference.
--- .vb file if VB.Net is the language ---
If Not (IsPostBack) Then
Try
Dim fr As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(New Uri("http://weblogs.asp.net/farazshahkhan")), System.Net.HttpWebRequest)
'In above code http://weblogs.asp.net/farazshahkhan is used as an example it can be different domain with different filename and extension
If (fr.GetResponse().ContentLength > 0) Then
Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
Response.Write(str.ReadToEnd())
End If
Catch ex As System.Net.WebException
Response.Write("File does not exist.")
End Try
End If
--- .cs file if C#.Net is the language ---
if (!(IsPostBack))
{
try {
System.Net.HttpWebRequest fr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri("http://weblogs.asp.net/farazshahkhan"));
//In above code http://weblogs.asp.net/farazshahkhan is used as an example it can be different domain with different filename and extension
if ((fr.GetResponse().ContentLength > 0)) {
System.IO.StreamReader str = new System.IO.StreamReader(fr.GetResponse().GetResponseStream());
Response.Write(str.ReadToEnd());
}
}
catch (System.Net.WebException ex) {
Response.Write("File does not exist.");
}
}
Once again seen lot of questions on the forum related to passing values from popup window to the parent form textbox. Specially when they have some GridView type control in the popup. In the following example I will be using two forms, parent form will be parent.aspx and popup will be popup.aspx. Also note that my parent.aspx form is derived from some MasterPage. Code is provided both in VB.Net and C#.Net.
--- .aspx of parent form ---
<script type="text/javascript">
function OpenPopup()
{
window.open("popup.aspx","List","scrollbars=no,resizable=no,width=400,height=280");
return false;
}
</script>
.
.
.
<asp:TextBox ID="txtPopupValue" runat="server" Width="327px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show List" />
--- .vb of parent.aspx if vb.net is the language ---
If Not IsPostBack Then
Me.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()")
End If
--- .cs of parent.aspx if C#.net is the language ---
if !(IsPostBack)
{
this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
}
--- .aspx of popup form ---
<script language="javascript">
function GetRowValue(val)
{
window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val; //hardcoded value used to minimize the code. ControlID can be passed as query string to the popup window
window.close();
}
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px" AllowPaging="True">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
--- .vb file if vb.net is the language ---
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
DirectCast(e.Row.FindControl("btnSelect"), Button).Attributes.Add("onclick", "javascript:GetRowValue('" & e.Row.Cells(1).Text & "')") 'assuming that the required value column is the second column in gridview
End If
End Sub
--- .cs file if C#.net is the language ---
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow)) {
((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells(1).Text + "')");
//assuming that the required value column is the second column in gridview
}
}
I hope the code above is straight forward and easy to understand.
Happy Coding!!!
Javascript to display continuous time on the Web page. By continuous it means that it will be displayed second by second.
<script type="text/javascript">
function ShowTime()
{
var dt = new Date();
document.getElementById("<%= TextBox1.ClientID %>").value = dt.toLocaleTimeString();
window.setTimeout("ShowTime()", 1000);
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
If you are using normal Webform then it can be called on Body load event. If you are using MasterPage then it can be called within ContentTemplate at the end afte all the controls will be rendered.
Seen a lot of questions regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript. So I thought to put it on my blog for quick reference for others and for myself. Following is the code:
------------------------------------------- .aspx code ---------------------------------------------
<script type="text/javascript">
function SelectAll(id)
{
var frm = document.forms[0];
for (i=0;i<frm.elements.length;i++)
{
if (frm.elements[i].type == "checkbox")
{
frm.elements[i].checked = document.getElementById(id).checked;
}
}
}
</script><!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
----------------------------------------- .vb file if VB.Net is the language ------------------------------------------
VB.Net Code
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.Header) Then
'adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")
End If
End Sub
----------------------------------------- .cs file if C#.Net is the language ------------------------------------------
C#.Net Code
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.Header))
{
//adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}
More Posts
Next page »