Asp.net TextBox post-back on each character entry


In This post I am going to Explain How to send a Request to asp.net server on every character entry in textbox control…

for this i am preparing a custom control with above functionality… named as PostBackTextBox..

First Take a Class Library Project and Delete Existing Classes then Add one class with name PostBackTextBox

Add System.Web Reference

Add System.Web Reference

and write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("PostBackTextBox.Scripts.PostBackTextBox.js", "text/javascript")]
namespace PostBackTextBox
{
    [Description("PostBackTextbox")]
    [ToolboxData(@"<{0}:PostBackTextBox Text="""" AutoPostBack=""true"" runat=""server""></{0}:PostBackTextBox>")]
     public class PostBackTextBox : System.Web.UI.WebControls.TextBox
    {
            public override string Text
            {
                get
                {
                    return base.Text;
                }
                set
                {
                    base.Text = value;

                    Attributes["value"] = value;
                }
            }
            public override bool AutoPostBack
            {
                get
                {
                    return true;
                }
                set
                {
                    base.AutoPostBack = true;
                }
            }
            protected override void AddAttributesToRender(HtmlTextWriter writer)
            {
                writer.AddAttribute("onkeyup", "Refresh(this.id);");
                writer.AddAttribute("onfocus", "SetCursorToTextEnd(this.id);");
                base.AddAttributesToRender(writer);
            }

            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                Attributes["value"] = Text;
                ClientScriptManager cs = this.Page.ClientScript;
                cs.RegisterClientScriptInclude("PBTBScript", cs.GetWebResourceUrl(this.GetType(), "PostBackTextBox.Scripts.PostBackTextBox.js"));
            }
        }
    }

and add one Folder with name Scripts and add one script file and set the script file properties as Build action is Embedded Resource

GoTo Script File Properties

Select Build Action As Embedded Resource

and add following code in script file

function Refresh(textControlID1) {
    __doPostBack(textControlID1, '');
};
function SetCursorToTextEnd(textControlID) {
    var text = document.getElementById(textControlID);
    if (text != null && text.value.length > 0) {
        if (text.createTextRange) {
            var range = text.createTextRange();
            range.moveStart('character', text.value.length);
            range.collapse();
            range.select();
        }
        else if (text.setSelectionRange) {
            var textLength = text.value.length;
            text.setSelectionRange(textLength, textLength);
        }
    }
}

DownLoadSampleCode

Advertisements

Control [ID] referenced by the ControlToValidate property of [ID] cannot be validated.


The above error will come when you are trying to validate asp.net checkbox with requiredfieldvalidator or any other validator by giving controltovalidate property as checkbox ID,

To Resolve this we need to validate checkbox without giving any Id as control to validate, so we need to use CustomValidator.

CustomValidator Doesn’t need any id, it needs only clientvalidationfunction or servervalidationfunction…

so the problem is solved…

Click this Link to get Solved Code

How to validate CheckBox Using Custom Validator


Write the code in .aspx page as follows…

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">
        function ClientValidationForCheckBox(sender, args) {
        var CheckBox1 = document.getElementById("<%=CheckBox1.ClientID %>")
            if (CheckBox1.checked == true) {
                args.IsValid = true;
            } else {
                args.IsValid = false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="CheckBox1" runat="server" />
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please Select CheckBox"
         ClientValidationFunction="ClientValidationForCheckBox"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

OutPut

Image

How to create DataTable and add primary key to DataTable in asp.net


Creating DataTable:
//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = "MyTable";
//add columns to datatable dt
dt.Columns.Add("ImgPath", typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType("System.String");
//giving column name
col.ColumnName = "Name";
//adding column to datatable dt
dt.Columns.Add(col);
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("Price", typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;

 

Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = "ImgPath";
dr[1] = "Name";
dr[2] = "Desc";
dr[3] = "123.45";
//adding datarow to datatable
dt.Rows.Add(dr);

Complete Asp.net Project On Entity Framework and crystal Reports


Hi Guys… On sep-21st-2012 My site completes 1 year so that i am providing free downlod of a project entitled as HOUSE FINANCE APPLICATION

This project includes

1.Asp.net

2.Ado.net

3.Crystal Reports

4.linq to entities

5.Jquery

6.Asp.net Ajax

7.Sql & Tsql

DownLoadDownloadProject

AJAX::SlideShow Extender Control Example


In this post we can learn how to do slideshow using ajax
Code in ASPX page:
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .style3
        {
            width: 353px;
        }
    </style>
</head>
<body>
<form id="form2" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr><td class="style3"></td>
<td align="center">
<asp:Label ID="Label1" runat="server"
Text="Label" style="font-size: x-large;
color: #FF3300; font-family: Arial, Helvetica, sans-serif;
font-weight: 700; background-color: #FFFFCC">
</asp:Label><br />
<asp:Image ID="Image2" runat="server" Height="299px"
Width="350px" />
<asp:SlideShowExtender ID="Image1_SlideShowExtender"
runat="server" AutoPlay="True" Enabled="True"
Loop="True" SlideShowServiceMethod="GetSlides"
SlideShowServicePath="" TargetControlID="Image1"
UseContextKey="True" ImageDescriptionLabelID="Label2"
ImageTitleLabelID="Label1" NextButtonID="Button3"
PlayButtonID="Button2" PlayButtonText="Play"
PlayInterval="1500" PreviousButtonID="Button1"
StopButtonText="Stop"></asp:SlideShowExtender>
<br /><asp:Label ID="Label2" runat="server" Text="Label"
style="font-size: x-large; color: #0000FF; font-family:
Verdana; background-color: #CCFFFF"></asp:Label><br />
<asp:Button ID="Button2" runat="server" Text="Previous" />
<asp:Button ID="Button3" runat="server" Text="Stop" />
<asp:Button ID="Button4" runat="server" Text="Next" />
</ContentTemplate>
</asp:UpdatePanel></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code behind:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static AjaxControlToolkit.Slide[] GetSlides(string contextKey)
    {
        AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[10];
        slides[0] = new AjaxControlToolkit.Slide("Images/0.jpg", "baby Image", "this is hd image from flikar");
        slides[1] = new AjaxControlToolkit.Slide("Images/1.jpg", "cutebaby image", "this is hd image from google");
        slides[2] = new AjaxControlToolkit.Slide("Images/2.jpg", "nicebaby", "this image from bing");
        slides[3] = new AjaxControlToolkit.Slide("Images/3.jpg", "goodbaby", "this image from asp.net info blog");
        slides[4] = new AjaxControlToolkit.Slide("Images/4.jpg", "nicebaby", "this also…");
        slides[5] = new AjaxControlToolkit.Slide("Images/5.jpg", "cutebaby", "this too…");
        slides[6] = new AjaxControlToolkit.Slide("Images/6.jpg", "smartbaby", "this one also…");
        //return default(AjaxControlToolkit.Slide[]);
        return slides;
    }

download Download Sample Code

How to apply distinct Method on particular column in LINQ


Sometimes we need to select two or more columns based on one column distinct
in this situation if we have one primary column and one columns allows duplicates so now we want to read these two columns based on column which allow duplicates… in this situation if we apply Distinct method it will takes records based on primary key column, it won’t read based on other column…
To do that….follows these steps…

first create one method for DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));
        }

and use this method to do Distinct based on Particular column…

var x = (from n in context.tblEmployees.Where(i => i.EMPLOYEE_ID == EmployeeId) select n).DistinctBy(i => i.EmployeeName).ToList();

Thanks…

……………HappyCoding……….