Monday, February 22, 2010

Bind a dropdown according to data in another drop down using traditional AJAX

Code for client side written within script:
function CallTemplate()

            {

           

              //alert(document.getElementById('cmbAssignTo_cmbSimple').value);

                   

                   var objDd=  document.getElementById('ddlmenu')

                  

                    var strValue = objDd.options[objDd.selectedIndex].value;                   

                   

                    //Create XMLHttpRequest object:'request'

                       

                        CreateXmlHttpRequestObject();

                       

                        //Build the required Query string

                        var sPass=1;

                       

                        var retrieveParam = 'id='+ strValue;

                       

                        var retrieveURL = "AJAX.aspx";

                        var url = retrieveURL + '?' + retrieveParam;

                       

                        request.open('GET',url,true);

                       

                        request.onreadystatechange = CheckTemplate;

                   

                        request.send(null);   

            }

               

            function CheckTemplate()

            {

                document.getElementById("ddlsubmenu").innerText="";

                if(request.readyState == 4 || request.readyState == 'complete')

                {

                    if(request.status == 200)

                    {   

                            var opt=document.createElement("option");

                            opt.value="-1";

                            opt.text="----select subcategory---";

                            document.getElementById("ddlsubmenu").add(opt);

                            var DdVisitTemp = document.getElementById("ddlmenu");

                           

                            var rootFile = request.responseXML.documentElement;

                         

                            var Id = rootFile.getElementsByTagName('Id');

                           

                            var Name = rootFile.getElementsByTagName('Name');

                           

                              if(Id.length > 0 || Name.length > 0)

                              {

                       

                                for(var i=0;i
                                {
                                   
                                       if(Name.length > 0)
                                       {
                                         var opt=document.createElement("option");
                                       
                                        opt.value=Id[i].text;
                                           
                                        opt.text=Name[i].text;
                                       
                                        document.getElementById("ddlsubmenu").add(opt);
                                       
                                      }
                                   
                                }
                               
                            }
                             
                    }//    inner IF       
           
            } // Outer IF
           
        }
       
        function CreateXmlHttpRequestObject()
            {
                try
                {
                    request = new XMLHttpRequest();
                }
                catch(nething)
                {
                    try
                    {
                        request = new ActiveXObject('Msxml2.XMLHTTP');
                    }
                    catch(othr)
                    {
                        try
                        {
                            request = new ActiveXObject('Microsoft.XMLHTTP');
                        }
                        catch(err)
                        {
                            request = false;
                        }
                    }
                }
                if(!request)
                {
                    alert("Error initializing XMLHttpRequest object!");
                }
            }



code for ajax page i.e ajax.aspx

private void Page_Load(object sender, System.EventArgs e)
        {
                   
                        string id=string.Empty ;
            System.Text.StringBuilder strXml;
            string passedValue = Request.QueryString["id"];

                        string strFill=" select  PK_PRIMARY_KEY,TITLE_SUBMENU from SUBJECT_SUBMENU where FK_SUBJECTMENU_ID = '" + id + "' ";
           
            DataTable dttemp= con.connectiondatatable(strFill);
           


            int j=dttemp.Rows.Count;
            strXml = new System.Text.StringBuilder ();
            strXml.Append("");
           
            if(j > 0)
            {
             
                for(int i=0 ; i
                {
                   
                    strXml.Append(""+dttemp.Rows[i]["PK_PRIMARY_KEY"].ToString() +" ");
                    strXml.Append(" "+dttemp.Rows[i]["TITLE_SUBMENU"].ToString()+" ");
                }

            }
            else
            {
               
                strXml.Insert(-1,"");
               
            }

            strXml.Append("");
            XmlDocument xTemplate = new XmlDocument();
            xTemplate.LoadXml(strXml.ToString());

            Response.ContentType = "text/xml";
            Response.CacheControl = "No-cache";
            xTemplate.Save(Response.OutputStream);
           
            // Put user code to initialize the page here
        }


There are two tables
1.SUBJECTMENU
2.SUBJECT_SUBMENU

Relation between them

SUBJECT_SUBMENU.FK_SUBJECTMENU_ID=SUBJECTMENU.PK_SUBJECTMENU_ID

Step 1:

create two tables must have relationship between them like above.

step 2:

Bind 1st dropdown on page load.

step 3:

Write code for client side as well as ajax page.

When u change 1st dropdown ,2nd dropdown will change.

How to create a ajax page:

Add a webform and delete all code that will bydefault in client except tag containing page inherit.

Example:
<%@ Page language="c#" Codebehind="AJAX.aspx.cs" AutoEventWireup="false" Inherits="KnowledgeSharing.AJAX" %>
except this one


Labels:

Encrypt web config in Asp.net

You can encrypt sections of a configuration file to protect sensitive

information used by your application. This improves security by making it difficult for unauthorized access even if an attacker gains access to your configuration file.

The .NET Framework includes two protected-configuration providers that can be used to encrypt sections of a configuration file.

· RSAProtectedConfigurationProvider, which uses the RSACryptoServiceProvider to encrypt configuration sections.

· DPAPIProtectedConfigurationProvider, which uses the Windows Data Protection API (DPAPI) to encrypt configuration sections.

The unprotected app.config file

This is what the app.config file looks like when it is unprotected:
<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<add name="SampleSqlServer" connectionString=   "Data Source=localhost;Integrated Security=SSPI;

  Initial Catalog=SampleDatabase;" />

</connectionStrings>

</configuration>
The protected app.config file

This is what the app.config file looks like when it is protected using the built-in .NET 2.0 framework ConfigurationSection.Protect () functionality:

Using RsaProtectedConfigurationProvider
<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <connectionStrings

 configProtectionProvider="RsaProtectedConfigurationProvider">

    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"

      xmlns="http://www.w3.org/2001/04/xmlenc#">

      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />

      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">

        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">

          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />

          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">

            <KeyName>RSA Key</KeyName>

          </KeyInfo>

          <CipherData>            <CipherValue>RXO/zmmy3sR0iOJoF4ooxkFxwelVYpT0riwP2mYpR3FU+r6BPfvsqb384pohivkyNY7Dm4lPgR2bE9F7k6TblLVJFvnQu7p7d/yjnhzgHwWKMqb0M0t0Y8DOwogkDDXFxs1UxIhtknc+2a7UGtGh6Di3N572qxdfmGfQc7ZbwNE=

            </CipherValue>

          </CipherData>

        </EncryptedKey>

      </KeyInfo>

      <CipherData>        <CipherValue>KMNKBuV9nOid8pUvdNLY5I8R7BaEGncjkwYgshW8ClKjrXSM7zeIRmAy/cTaniu8Rfk92KVkEK83+UlQd+GQ6pycO3eM8DTM5kCyLcEiJa5XUAQv4KITBNBN6fBXsWrGuEyUDWZYm6Eijl8DqRDb11i+StkBLlHPyyhbnCAsXdz5CaqVuG0obEy2xmnGQ6G3Mzr74j4ifxnyvRq7levA2sBR4lhE5M80Cd5yKEJktcPWZYM99TmyO3KYjtmRW/Ws/XO3z9z1b1KohE5Ok/YX1YV0+Uk4/yuZo0Bjk+rErG505YMfRVtxSJ4ee418ZMfp4vOaqzKrSkHPie3zIR7SuVUeYPFZbcV65BKCUlT4EtPLgi8CHu8bMBQkdWxOnQEIBeY+TerAee/SiBCrA8M/n9bpLlRJkUb+URiGLoaj+XHym//fmCclAcveKlba6vKrcbqhEjsnY2F522yaTHcc1+wXUWqif7rSIPhc0+MT1hB1SZjd8dmPgtZUyzcL51DoChy+hZ4vLzE=

        </CipherValue>

      </CipherData>

    </EncryptedData>

  </connectionStrings>

</configuration>

Using  DataProtectionConfigurationProvider

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">

    <EncryptedData>

      <CipherData>        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAC604ocVBjE6iwNotzM4ZMQQAAAACAAAAAAADZgAAqAAAABAAAABWwjYy7bwZdDql3nImdFcfAAAAAASAAACgAAAAEAAAAK/xpOyKKzMSGwg/XsFAi/5gAQAAVOSKtGe5k21uyyxt35111auSE746lH5Ij8E1839D9e/eoFKvxCXFkBtlQD/sftjEGzfrmeTQQMMP2c5kWCGINH1N5NOReK+vOxZHQzkUJxn4D2fOxknLrprMvnRawhPmuqLcHC3iZTxWnxYL9pSGs3Gk9bEbhhFFNZN/0AvJ6OlqfvhpaI6zA1NIbS4MYcQ3lAsmupjE4deOB7ocTooJTWoToAxVJ0gC+hJnQ7ZwHiQLUIGmeaAs8nt7t8NJSWMhsFHbYzjpSGO4q8Iet1xsCnbxo5CH/N9mdC8SZ9Nz4XLt9TlmWJhjFIuCbv7YoqhI8895EQsOsQ9VumFaj1jIqNHMS8lWLcZULC7ZM1Yn/Dvhk+bNgaljLNRotdPeMIwLAbqVUY9kzeM1alVbFNkmC0uvApCli4lAq5n9rNyK5xktzxbA0QFRrI2W1A9ns3Y6g5Jcy9ztdEVfSbU+jGkvPBQAAACdTt+x46DXMgPiRLp9lMd36IFWsA==</CipherValue>

      </CipherData>

    </EncryptedData>

  </connectionStrings>

</configuration>
How this was done

In order to protect a section of the app.config file, we can use the ProtectSection() function to encrypt that portion of the file. There is no need to unprotect the section. We can still read the information from the section; the built-in configuration manager will automatically decrypt the cipher text.

private void ProtectSection(string sectionName)

{

    // Open the app.config file.

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

   

    // Get the section in the file.

    ConfigurationSection section = config.GetSection(sectionName);

   

    // If the section exists and the section is not readonly, then  

    // protect the section.

    if (section != null)

    {

        if (!section.IsReadOnly())

        {

            // Protect the section.

            section.SectionInformation.ProtectSection ("RsaProtectedConfigurationProvider");

            section.SectionInformation.ForceSave = true;

            // Save the change.

            config.Save(ConfigurationSaveMode.Modified);

         }

     }

}
Getting the value

As stated above, there is no need to unprotect or decrypt the app.config file to get the value of the connection string; the decryption is handled by the .NET 2.0 framework. Simply open the app.config file and read the value of the connection string, like this:

// Open the app.config file.

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Display the current connection string.

txtConnString.Text = config.ConnectionStrings.ConnectionStrings["SampleSqlServer"].ConnectionString;

Labels:

How to restrict user to copy from a textbox or paste text to textbox using javascript

This code demonstrate how to restrict user to copy from a textbox or paste text to textbox using JavaScript.

Here is the code :
<script language="javascript">

function copy() {

    alert("Can't copy the text");

    return false;

}

function paste() {

    alert("can't paste text");

    return false;

} 

</script>

<asp:TextBox ID="TextBox2" runat="server" Text="hi" oncopy="return copy();" onpaste="return paste();"></asp:TextBox>



Thanks,
Abhay

Labels:

How to use autocompleteTextbox in Ajax

It is easier for user searching a text when you enter some text, the all text begin with with that text will show so that you can chose it and go for searching.the type of thing is used by google seach,wikimapedia etc.i have used in my project.

First you have install ajaxtoolkit ,add reference of it in your application.

ADD ScriptManager then add a textbox.

Drag and drop AutoCompleteExtender from it then the code will be like this
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<body>

    <form id="form1" runat="server">

    <div>

      <asp:ScriptManager ID="ScriptManager1" EnablePageMethods=true runat="server">

        </asp:ScriptManager>

    <asp:TextBox ID="txt1" runat=server ></asp:TextBox>

  

    <cc1:AutoCompleteExtender

    runat="server"

    ID="autoComplete1"

    TargetControlID="txt1"//target control

    ServiceMethod="Getdata"//method should be pagemethod

    MinimumPrefixLength="1" //minimum character for showing data

    CompletionInterval="100"//completioninterval

    EnableCaching="true"

    CompletionSetCount="20"

     >

      

</cc1:AutoCompleteExtender>

     

    </div>

    </form>

</body>
Then goto serverside

add namespace
using System.Web.Services;
But reference for webservice added before if not then add first.

Write function for getting data
[WebMethod]//MUST BE USED BEFORE FUNCTION

//METHOD MUST BE STATIC

           public static string[] Getdata(string text, int count)

          {

          

                      string sql = "Select name from  L_PHYSICALEXAM Where name like @text";

            SqlConnection conn = new SqlConnection( your connection string);

            SqlDataAdapter da = new SqlDataAdapter(sql,conn);

           

            da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = text+ "%";

            DataTable dt = new DataTable();

            try

            {

                da.Fill(dt);

            }

            catch(System.Exception er)

            {

                string st = er.ToString();

            }

         

            string[] items = new string[dt.Rows.Count];

            int i = 0;

            foreach (DataRow dr in dt.Rows)

            {

               items.SetValue(dr["Name"].ToString(),i);

  i++;             }

            return items;

          

        }
When you enter first character it will start show those data starting from that character from database.

Labels:

How to pass value from parent page to pop up without using querystring

If you want pass some value from parent page to pop up without using query string then you can pass it as argument.

Take this example

For modalDialogue:

var retnBlood = window.showModalDialog("path of the pop up page, pass your argument, "status:No;dialogHeight:400px;dialogWidth:600px;resizable:0;scrollbars:1;center:yes");

You can find the value of argument in modal dialogue by this code

For Modal Dialogue:
function Show()

{

 var argVal = window.dialogArguments;

//save it in a hiddenfield as use it

}
Call this function at pageload using below code
protected void Page_Load(object sender, EventArgs e)

{               

ClientScript.RegisterStartupScript(this.GetType(), "alert", "&ltscript&gtShow();&lt/script&gt");

}
If you are using simple pop up instead of modal dialogue then use like below
function Show()

{

 var argVal = Window.opener;

//save it in a hiddenfield as use it

}

Thanks,
Abhay

Labels:

How to refresh parent page on close of popup

This shows how to refresh parent page on close of popup

For Pop up:
function CloseAndRefresh() 
{
    window.opener.location.href = window.opener.location.href;
    window.close();
}
function OpenModal()

{             

    window.showModalDialog('page.aspx'); 

    window.location.reload();

}


Thanks,
Abhay

Labels:

How to call a serverside method in ASP.NET using javascript

Sometime we need to do something on client side, no postback will be there for that we can call server side method from client side.

For example I need information for binding a drop down to bind another drop down.
on change of drop down I will call javascript function.

<asp:dropdown id=ddlDropdown runat=server/>
on page load
ddlDropdown.Attributes.Add("onchange","callMethod();")
<script langauge=javascript type="text/javascript">

function callMethod()

{

var pkval = Document.getElementbyId("ddlDrop").value;

PageMethods.FindData(pkVal,OnSucceeded,OnFailed);//finddata is serverside static method.

}

function OnSucceeded(result)

    {

         FillData(result);       

     }

   

    

    function OnFailed(error, userContext, methodName)

    {

       

 alert("failure")  ;  

    }

</script>
on serverside

add namespace
using System.Web.Services;

write code for that method

  [WebMethod]//must be there or without adding using System.Web.Services; you directly add here

[System.Web.Services.WebMethod]

public static string RetriveData(string args)

        {

  int id = convert.Toint32(args);

//create a dataset use sql query like (where pkid = id)from another table

// remember the column will be your xml node so you can rename in your query like like pk_primary as pk

 DataSet dsData= //add code as your requirement

//after creating dataset convert to xml

 dsData.DataSetName = "CONTROLS";

            XmlDataDocument xDoc = new XmlDataDocument(dsData);

            string xml = xDoc.OuterXml;

            xml = xDoc.InnerXml;

            return xml;

}
result xml file does to here
function OnSucceeded(result)

    {

         FillData(result); // call another function      

     }

function FillData(xmlVal)

{

  //find the node values

  var doc=new ActiveXObject("Microsoft.XMLDOM");

        doc.async="false";

        doc.loadXML(result);

  var controls = doc.getElementsByTagName('Table');

 for(var i = 0; i < controls.length ; i++)

            {

var Contol_type = controls[i].getElementsByTagName('columnname as you assign in query in serverside')[0].childNodes[0].nodeValue;

//assign that Contol_type  to a another control or dropdown

            }

}
This is an example of how to call serverside method.

Labels: , ,

How to calculate End date after adding some days to startdate

sometimes we need to calculate a date after adding some duration to a date just for example doctor pescribe a medicine for some days so end date will be today + some duration.

we have to do it in clientside in javscript function write these

//USES MASTER PAGE
  function CalculateEndDate()
{
  var startTime =  document.getElementById('<%=txtstartDate.ClientID%>').value;//START DATE

            var objvalDur = document.getElementById('<%=ddlDuration.ClientID%>').value;//duration

//calculate end date

   var d = new Date(startTime);

                    d.setDate(d.getDate()+durTime);

                    var exactDate = (d.getMonth()+1)+"/"+d.getDate()+"/"+d.getYear();

                    document.getElementById('<%=txtendDate.ClientID%>').value=exactDate;

}

Labels:

How to stop inserting data after refresh in asp.net

When you click refresh button it always do again the last action performed.you can stop inserting data for that page where you actually want to insert data once not again and again.just for example in registration page you have submit data once.if you submitting articles or posting answer you may have do it again and again remaining in same page.

so this the code i have used in a project to stop inserting data where you want to insert data once not again and again.

1.create a hidden field and add some code to form tag.

<form id="Form1" method="post" runat="server" onsubmit="var o=getElementById('__STATUSREFRESH');var i=Number(o.value);i++;o.value=i;">

            <input id="__STATUSREFRESH" type="hidden" value="1" name="__STATUSREFRESH" runat="server">

2. Add these code to serverside

private bool IsRefreshCheck;

private bool RefreshStamped;

private bool IsRefresh

        {

            get

            {

                if (!this.RefreshStamped)

                    this.IsRefreshCheck= checkRefresh();

                return this.IsRefreshCheck;

               

               

            }

        }

private bool checkRefresh()

        {

            this.RefreshStamped= true;

            string stampKey = String.Concat(this.ToString(), "_STATUSREFRESH");

            int prevStamp = getValue(this.Session[refreshCheck] as string);

            int stamp = getValue(this._STATUSREFRESH.Value);

            if (stamp > prevStamp) // Postback

            {

                this.Session[refreshCheck] = stamp.ToString();

                return false;

            }

            return true;

        }

//THEN CHECK

if (!this.IsRefreshCheck==true)//THERE WAS NO REFRESH BUTTON CLICKED if clicked then last action willnot performed

{

// DO THE ACTION

}

Labels: ,

How to set focus after the text in the textbox

This code demonstrate how to set focus after the text in the textbox.

Design code :

<input type="button" id="idbtn" value="Set" onclick="func();" />

 <asp:TextBox ID="TextBox1" runat="server" Text="hi"></asp:TextBox>


JavaScript code :

<script language="javascript">

function func()

{

    var txt1= document.getElementById("TextBox1");

    txt1.focus();//set focus

    txt1.value = txt1.value; //set value

}

</script>


Thanks,
Abhay

Labels:

How to check a year is leap year or not using SQL function

Create a function to check leap year

create FUNCTION CHECK_LEAP_YEAR

(@year SMALLINT)

RETURNS BIT

AS

BEGIN

    DECLARE @leapdate SMALLDATETIME

    DECLARE @check_day TINYINT

    SET @leapdate = CONVERT(VARCHAR(4), @year) + '0228'

    SET @check_day = DATEPART(d, DATEADD(d, 1, @leapdate))

    IF (@check_day = 29)

        RETURN 1

    RETURN 0

END

SELECT dbo.CHECK_LEAP_YEAR(2000) as checkLeapYear

Run above query and pass the year, if it is leap year the result will be returned as 1 if not then 0.

Labels:

How to change the key value present in web config dynamically

Suppose there is a key present in web config and which have the value 10.

Example:

<add key="Unit" value="10" />

You can modify the value programmatically using this code

Code Behind :

Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");

webConfigApp.AppSettings.Settings["Unit"].Value = "15";

webConfigApp.Save();

Namespace Required:

using System.Configuration;

using System.Web.Configuration;

Labels:

Disable all dates except current date in calender control using c#

You can disable all dates except current date programmatically.You can also change the background color dyanamically.

Calender control

<asp:Calendar ID="Calendar1" runat="server" OnDayRender="Calendar1_DayRender" ></asp:Calendar>

Code Behind

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

{

if (e.Day.Date > DateTime.Now.Date || e.Day.Date < DateTime.Now.Date)

{

e.Cell.Enabled = false; //disable current date

}

else

{

e.Cell.BackColor = System.Drawing.Color.Blue;//You can change color of the current date

}

}

Labels: ,

Code for showing floating div in a webpage

In your project if you need to show data in a floating div mean div will appear over the web page then use this html code and javascript function to hide the div.There is div in below code whose id "DivText" that can used to to bind data.There is also a crose sysmbol to close the div.This is useful when you need to show data onmouseover of gridview or repeater.

< div id="popDiv" runat="server" style="position:

absolute; width: 320px; border: solid 1px #96c1e7;margin:

 25px 0px 0px 20px; background-color: #ffffff;

 display: none; z-index: 2;opacity: 0;

padding: 5px; overflow: auto;">

  < div align='right'>

 < a runat='server' id='A2' title='Close' href='javascript:void(0);' style='background-color: #666666;color: #FFFFFF;

font-weight: bold; font-size: 13px;

text-decoration: none; border: outset thin #FFFFFF;

padding-left: 5px; padding-right: 5px;

padding-bottom: 5px;' onclick='CloseDiv();'>

X< /a>

< /div>

< br />

< div align="left" id="DivText" runat="server" style="width: 300px;">

< /div>

< /div>

Javascript function

function CloseDiv()

{
document.getElementById("popDiv").style.display = 'none';

}

Labels:

Create custom alphabetic pagination in gridview or datagrid or repeater

If you want to bind the grid or repeater alphabetically means there will be alphabets and onclick of alphabet the grid will bind accordingly the clicked alphabet.

For this you need create a gridview or datagrid or repeater according to your requirement and a datalist which will be used for paging.

Here I am giving an example with datagrid.You can alos replace this with gridview or repeater.

Datagrid code

<asp:datagrid id="DGrid_article" runat="server"

cellspacing="0" cellpadding="0" allowsorting="True"

allowpaging="false" autogeneratecolumns="False"

datakeyfield="ARTICLE_ID" showheader="false"

width="500" AlternatingItemStyle-ForeColor="#6600ff">

<columns>

<asp:TemplateColumn>

<ItemTemplate>

<table style="display:none">

<tr>

<td>

<label runat="server" id="lblPk">

    <%# DataBinder.Eval(Container.DataItem, "article_id")%>

</label>

</td>

</tr>

</table>

</ItemTemplate>

</asp:TemplateColumn>

<asp:buttoncolumn visible="false" commandname="Select"></asp:buttoncolumn>

<asp:boundcolumn datafield="HEADING" itemstyle-width="160"&GT&LT/asp:boundcolumn>

<asp:boundcolumn datafield="NAME" itemstyle-width="120"&GT&LT/asp:boundcolumn>

<asp:boundcolumn datafield="UPLOAD_TIME" itemstyle-width="160"></asp:boundcolumn>

<asp:TemplateColumn>

<ItemTemplate>

<input id="btn" type="button" onclick="inf(this.id);" value="SHOW" runat="server" NAME="btn"

style="COLOR: #0000ff; BACKGROUND-COLOR: bisque">

</ItemTemplate>

</asp:TemplateColumn>

</columns>

</asp:datagrid>

Datalist to create custom paging

<asp:datalist id="DLst_Alphabets" runat="server"

repeatcolumns="13" repeatdirection="Horizontal">

<itemtemplate>

  

<asp:linkbutton id="LBtn_SelectAlphabet" runat="server"

 commandname="SearchByAlphabet"

commandargument='<%# DataBinder.Eval(Container, "DataItem") %>'

oncommand="LBtn_SelectAlphabet_Command">

<%# DataBinder.Eval(Container, "DataItem") %>

</asp:linkbutton>

</itemtemplate>

</asp:datalist>

Code to create alpthabets

public void BindAlphabetList()

{

DLst_Alphabets.DataSource = GetAlphabetList();//get the alphabets

DLst_Alphabets.DataBind();//bind

}

public char[] GetAlphabetList()

{

char[] L_AlphabetList = new char[26];

for(byte AlphaCtr = 65; AlphaCtr <= 90; AlphaCtr++)

{

L_AlphabetList[AlphaCtr - 65] = System.Convert.ToChar(AlphaCtr);

}

return(L_AlphabetList);

}

Binding Grid code

private void BindarticleList(string str)

{

           

string searchpattern ="select HEADING,ARTICLE_ID,NAME,UPLOAD_TIME FROM LOGIN,USER_ARTICLE WHERE LOGIN.PK_USER_ID=USER_ARTICLE.FK_USER_ID AND ROWSTATUS=1 and HEADING LIKE '"+str+"%'";//your query

connection ob = new connection();

DGrid_article.DataSource=ob.connectiondatatable(searchpattern);

DGrid_article.DataBind();//bind the grid

if(DGrid_article.Items.Count > 0)

lblDisplayMssg.Text="Total "+DGrid_article.Items.Count+" no of articles  available ";//show total no of itenms starts with this alphabets (this is optional)

}

//Onclick of alphabets Grid Binding Code

protected void LBtn_SelectAlphabet_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)

        {

LinkButton LBtn_SelectAlphabet = (LinkButton)sender;

LBtn_SelectAlphabet.FindControl(LBtn_SelectAlphabet.ID);

LBtn_SelectAlphabet.ForeColor = System.Drawing.Color.Red;

BindarticleList(e.CommandArgument.ToString());//call bind function to bind the grid

Lbl_SearchDescription.Text = "Showing articles whose begins with "" + e.CommandArgument.ToString() + "".";//add lebel which option to show that items strat with this alpthabet

        }

//Page load action

private void Page_Load(object sender, System.EventArgs e)
{
   
if(!Page.IsPostBack)
{
this.BindAlphabetList();//bind the datalist to show alphabets
Lbl_SearchDescription.Text="Showing articles whose  begins with "" + "A" + "".";
BindarticleList("a");//bind grid starts with "a"
}
}

Note: You can use gridview and repeater instead of datagrid

Labels: ,

Render your ASP.NET webpage in IE8 With simillar functionality of IE7

Some of the controls like repeater control isn't working well in IE8 means you can realize the UI changes occured while opening the page with IE8. So If your ASP.net application is working fine in IE6 and IE7 ,But not working well in IE8 ,So if you want this functionality in IE8 then do as below.

There are two methods by which you can achieve this.

First one:

Go to IIS and spot your website and right click on it and go to properties and add a HttpHeader with HeaderName as ‘X-UA-Compatible’ and value as ‘IE=EmulateIE7’

Second one:

add this after head tag in each page
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

But make sure that no script tag and link preceding this one
you can also add meta tag programmatically in OnInit event

protected override void OnInit(EventArgs e)

{

//Always do the check before adding the meta tag

if (CheckBrowser("IE", 8))

{

HtmlMeta meta = new HtmlMeta();

meta.HttpEquiv = "X-UA-Compatible";

meta.Content = "IE=EmulateIE7";

this.Page.Header.Controls.AddAt(0, meta);

}

}

/// Checks the browser.

/// </summary>

/// <param name="browserName">Name of the browser.</param>

/// <param name="browserMajorVersion">The browser major version.</param>

/// <returns></returns>

public static bool CheckBrowser(string browserName, int browserMajorVersion)

{

HttpBrowserCapabilities br = HttpContext.Current.Request.Browser;

if (br.Browser.ToUpper().Equals(browserName) && (br.MajorVersion == browserMajorVersion))

return true;

else

return false;

}
Note:All these applies when compatibility mode isn't selected in IE8.(To view compatibility mode go to tool and then compatibility view setting)

Labels:

How to Export gridview or repeater data to Excel

You can export the data of gridview to a excel file programmatically.
First add a gridview inside the form tag which must have runat="server"

example:
<asp:GridView ID="GridView1" runat="server">

</asp:GridView>
Bind the grid at page load
protected void Page_Load(object sender, EventArgs e)

{

   if (!IsPostBack)

   {

        BindGrid();

   }

}

private void BindGrid()

{

     string strFillgird = //yopur query

     //create a dataset here

     GridView1.DataSource = dsRecord;

     GridView1.DataBind();

}
Call this function to Export data whenever you require like onclick of button or linkbutton
private void ExportData()

{

  string FileName = "MyExcel.xls";

  //clear buffer

  Response.Clear();

  //display  Download dialog

  Response.AddHeader("content-disposition", "attachment;filename=" + FileName + "");

  Response.Charset = "";

  Response.Cache.SetCacheability(HttpCacheability.NoCache);

  Response.ContentType = "application/vnd.xls";

  System.IO.StringWriter ioWriter = new System.IO.StringWriter();

  System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(ioWriter);

  GridView1.RenderControl(htmlWriter);

  Response.Write(ioWriter.ToString());

  Response.End();

}
add this method to render gridview control

//If you are using master page
public override void VerifyRenderingInServerForm( Control control )

{

}
Note:Set EnableEventValidation as false

Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm46.aspx.cs" Inherits="DermsoftV2.Test.WebForm46" EnableEventValidation = "false"%>

Labels:

How to show confirm message with Yes and No button instead of Ok and Cancel button

Description

In javascript we usually show confirm message with this like code

var retVal = confirm(" Do you still want to Navigate ?");

return retVal;


If you click Ok button in cofirm message it will return true and if you click cancel it will return false.We can also replace Ok and Cancel with Yes and No.

Check Below code

<script language=javascript type="text/javascript">

   function window.confirm(str)

   {

      execScript('n = msgbox("' + str + '","4132")', "vbscript");

      return (n == 6);

   }

   function ShowConfirm()

   {        

      if (confirm("Do you want to delete this item") == true)

      {

        return true;

      }

      else

      {

        return false;

      }

   }

   function show()

   {

     var bAdd = ShowConfirm();

     return bAdd;           

   }   

</script>



    <asp:Button ID="BtnShow" runat="server" Text="Button" OnClientClick="return show();"/>



Note:It works only in IE



Thanks,
Abhay

Labels:

How to put a radcombobox or any 3rd party controls inside infragistic ultrawebgrid

Some days back I faced a problem that I needed a radcombobox inside a infragistic ultrawebgrid control.

I thought it is quite impossible to put one 3rd paty contyrols inside another 3rd party controls.Then finally i solved that problem.

The ultrawebgrid have ethier own column properties for creating a column of checkbox type or dropdown type or hidden column or only column .

Example:
UltraGridColumn checkSend = new UltraGridColumn();

checkSend.Header.Caption = sendHeader;

checkSend.Type = ColumnType.CheckBox;
Here column type is checkbox .You can make it dropdown also.But my requirement was to have a radcombox box.

To put radcombox or any combobox or 3rd party controls you can use this code.

First create a template column and assign a key value .
TemplatedColumn col = new TemplatedColumn();

    col.Key = "Pharamcy";

    col.HeaderText = "PharmacyList";

    col.Width = Unit.Percentage(12);

   PlaceHolderTemplate temp = new PlaceHolderTemplate();

   col.CellTemplate = temp;

      //add that column to the web grid
   UltragridPres.Bands[0].Columns.Insert(UltragridPres.Bands[0].Columns.Count, col);
Then create a class to describe the structure of the column template and that class must implement ITemplate interface.

See this class :
public class PlaceHolderTemplate : ITemplate

{

public void InstantiateIn(System.Web.UI.Control container)

{

CellItem cellitem = (CellItem)container;

//Declare the control (or controls) you wish to put into the column template

RadComboBox PharamacyList = new RadComboBox();//dyanamic create a radacombobox .you can craete you own controls

cellitem.Controls.Add(PharamacyList); //Adds the control to the column template for this row

//cellitem.Cell.AllowEditing = AllowEditing.No; //Don't want to actually be able to edit the cell, just

}

}
Then create the function for creating controls.Here we set the ID property for the controls that we added in the instantiatein method,and attach an event handler for one of the control's events.This step is required to hook up the event handler. All other properties should be set in the InitializeRow event.If you are not setting a server-side event handler for the control, you do not need to override the CreatChildControls method, and should do everything in the InitialzieRow event.Since we have access to the grid object, we again have the opportunity to set properties based on a number of criteria, including the value of another cell in the row.You should ensure that you get the right controls that you put into the specific rows in the instantiate in. Otherwise you will get an InvalidCast exception. In this example, we put an combox into each row with "Phramacy" value.
protected override void CreateChildControls()

{

Infragistics.WebUI.UltraWebGrid.TemplatedColumn col = (TemplatedColumn)UltragridPres.Columns.FromKey("Pharamcy");

base.CreateChildControls();

for (int i = 0; i < UltragridPres.Rows.Count; i++)

{

RadComboBox PharamacyList = (RadComboBox)((CellItem)col.CellItems[i]).Controls[0];

PharamacyList.ID = "PharamacyList";//id

PharamacyList.Width = Unit.Pixel(80);

PharamacyList.Height = Unit.Pixel(80);

PharamacyList.ExpandAnimation.Type = AnimationType.OutSine;

PharamacyList.DropDownWidth = Unit.Pixel(150);

// add clientside event and that function must be declared at client end

PharamacyList.OnClientDropDownClosed = "OnClientDropDownClosed";

PharamacyList.OnClientItemsRequesting = "OnClientItemsRequesting";

PharamacyList.OnClientDropDownOpening = "OnClientDropDownOpening";

PharamacyList.HighlightTemplatedItems = true;

PharamacyList.ShowMoreResultsBox = true;

PharamacyList.EnableLoadOnDemand = true;

PharamacyList.Skin = "Hay";

PharamacyList.BackColor = System.Drawing.ColorTranslator.FromHtml("#EDFBE1");

PharamacyList.NoWrap = true;

PharamacyList.EmptyMessage = "Type to search ";//set empty message

//add handler to populate data when item requested

PharamacyList.ItemsRequested += new RadComboBoxItemsRequestedEventHandler(PharamacyList_ItemsRequested);

}

}
The item request event of combobox:
protected void PharamacyList_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)

{

RadComboBox ob = (RadComboBox)o;

ob.Items.Clear();

string sqlSelectCommand = //your query

then create a datatable

DataSet ds = SqlHelper.ExecuteDataset(new Connection().GetCon, CommandType.Text, sqlSelectCommand);

DataTable dtAllData = ds.Tables[0];

ob.DataTextField = "NAME";

ob.DataValueField = "NO";

ob.DataSource = dtAllData;

ob.DataBind();

}
Ensures that the TemplatedColumn is properly instantiated.So add this event
private void UltragridPres_TemplatedColumnRestored(object sender, Infragistics.WebUI.UltraWebGrid.ColumnEventArgs e)

{

if (((TemplatedColumn)e.Column).CellTemplate == null)

{

((TemplatedColumn)e.Column).CellTemplate = new PlaceHolderTemplate();

}

}

}

}
This UltragridPres_TemplatedColumnRestored method must be invoked in OnInit event.So add this eventhandler in the OnInit event.

See below code:
override protected void OnInit(EventArgs e)

{

InitializeComponent();

base.OnInit(e);

}

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.UltragridPres.TemplatedColumnRestored += new Infragistics.WebUI.UltraWebGrid.TemplatedColumnRestoredEventHandler(this.UltragridPres_TemplatedColumnRestored);

}
You must need the code for creating ultrawebgrid:

Metatag:
<%@ Register Assembly="Infragistics35.WebUI.UltraWebGrid.v8.2, Version=8.2.20082.1000, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb"

    Namespace="Infragistics.WebUI.UltraWebGrid" TagPrefix="igtbl" %>
Ultrawebgrid controls:
<igtbl:UltraWebGrid ID="UltragridPres" runat="server" Width="100%">

                            <Bands>

                                <igtbl:UltraGridBand>

                                    <AddNewRow View="NotSet" Visible="NotSet">

                                    </AddNewRow>

                                </igtbl:UltraGridBand>

                            </Bands>

                            <DisplayLayout AllowColSizingDefault="Free" AllowDeleteDefault="Yes" ScrollBarView="Vertical"

                                AllowUpdateDefault="Yes" BorderCollapseDefault="Separate" Name="UltraWebGrid1"

                                RowHeightDefault="20px" SelectTypeRowDefault="Single" TableLayout="Fixed" Version="4.00"

                                AllowAddNewDefault="Yes" SelectTypeCellDefault="Single" CellClickActionDefault="RowSelect"

                                CompactRendering="False" StationaryMargins="Header" ColHeadersVisibleDefault="Yes">

                                <FrameStyle BackColor="Window" BorderColor="InactiveCaption" Font-Names="Microsoft Sans Serif"

                                    Font-Size="8.25pt" Width="100%" Height="200px">

                                </FrameStyle>

                                <Pager MinimumPagesForDisplay="2">

                                    <PagerStyle BackColor="LightGray" BorderStyle="Solid" BorderWidth="1px">

                                        <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" />

                                    </PagerStyle>

                                </Pager>

                                <EditCellStyleDefault BorderStyle="None" BorderWidth="0px">

                                </EditCellStyleDefault>

                                <FooterStyleDefault BackColor="LightGray" BorderStyle="Solid" BorderWidth="1px">

                                    <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" />

                                </FooterStyleDefault>

                             

                                <HeaderStyleDefault Height="0px" BackColor="#006699" BorderWidth="1px" BorderStyle="Solid"

                                    VerticalAlign="Middle" HorizontalAlign="Left" Font-Bold="true" ForeColor="White">

                                    <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" ColorBottom="Gray"

                                        WidthTop="1px" ColorRight="Gray" />

                                </HeaderStyleDefault>

                                <RowSelectorStyleDefault BorderColor="#006699">

                                    <BorderDetails StyleBottom="None" StyleLeft="None" StyleRight="None" StyleTop="Solid" />

                                </RowSelectorStyleDefault>

                                <RowStyleDefault BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" Font-Names="Microsoft Sans Serif"

                                    Font-Size="8.25pt" Cursor="Hand">

                                    <Padding Left="3px" />

                                    <BorderDetails ColorLeft="Window" ColorTop="Window" />

                                </RowStyleDefault>

                                <RowAlternateStyleDefault CssClass="gridAlternateItem">

                                </RowAlternateStyleDefault>

                                <SelectedRowStyleDefault CssClass="girdSelectedItem" Cursor="Hand">

                                </SelectedRowStyleDefault>

                                <ActivationObject BorderColor="" BorderWidth="">

                                </ActivationObject>

                            </DisplayLayout>

                        </igtbl:UltraWebGrid>

Labels:

How to disable or make readonly all controls in a page

Sometimes you might be need to make all textboxes or checkbox as readonly or disable.For example if you check a checkbox in a page then all the textbox should be disabled or readonly.

Use this code
<script language=javascript>

        function check() {

            for (var i = 0; i &lt document.forms[0].elements.length; i++) 
          {

               var element = document.forms[0].elements[i];

                switch (element.type) {

                    case 'text'://textbox type

                        document.forms[0].elements[i].readOnly = true;

                        break;

                    case 'select-one'://dropdown

                        document.forms[0].elements[i].readOnly = true;

                        document.forms[0].elements[i].disabled = true;

                        break;

                    case 'checkbox'://checkbox

                        document.forms[0].elements[i].disabled = true;

                        break;

                    case 'radio'://radiobutton

                        document.forms[0].elements[i].disabled = true;

                        break;

                    case 'button'://button

                       

                        document.forms[0].elements[i].disabled = true;

                        break;

                    case 'submit'://button

                       

                        document.forms[0].elements[i].disabled = true;

                        break;

                    case 'textarea'://textarea

                        document.forms[0].elements[i].readOnly = true;

                        break;

                }

            }

        }

   

    </script> 

Labels:

How to set empty message when AllowCustomText is set to false in Radcombobox

Recently i faced problem in radcombox which is product of telerik. Telerik products are gaining popularity day by day .So i feel that if someone has this problem then it might be helping him.

Radcombobox has a property called AllowCustomText which means user can type something and result will be shown in dropdown .Radcombobox has also a property called EmptyMessage means when nothing is selected empty message will be shown.Example you set "select" as empty message then it will display when nothing is selected.

But problem is that i want to show this empty message but i want AllowCustomText to be false.Then if AllowCustomText is false then set empty message isn't working.I got a solution that is to make AllowCustomText as true and don't allow user to type something in combo.Here I am giving the code

Radcombobox:


<telerik:RadComboBox ID="RadComboBoxDispenseQ" runat="server" Height="170px" Width="100%"EnableLoadOnDemand="true" Style="margin: 0 auto 0 0px; display: block !important;EmptyMessage="Select Qualifier" AllowCustomText="true" ToolTip="Select Dispense" ExpandAnimation-Type="InCubic" Skin="Hay" ZIndex="10000000" LoadingMessage="LOADING" BackColor="#EDFBE1" DropDownWidth="200" >
</telerik:RadComboBox>

I set AllowCustomText="true" in the above combo
You need to add javascript code not to allow user to type.

<script type="text/javascript"&gt

//pageload add handler to that combo

  function pageLoad() {

            var combo = $find("<%= RadComboBoxDispenseQ.ClientID %>");
            var input = combo.get_inputDomElement();
            input.onkeydown = onKeyDownHandler;//handler added

           }

    //FOR DISABLE KEY PRESS of comboobox

    function onKeyDownHandler(e) {

        if (!e)

            e = window.event;

        e.returnValue = false;

        if (e.preventDefault) {

            e.preventDefault();

        }

    }

</script>
Thanks


Labels:

How to read and write textfiles using javascript

You can read and write to a text files using javascript.It is working in IE6 and IE7.Just you need go to tools ->internet options ->Security -> Custom level -> then mark Initialize and script ActiveX controls not marked as safe as Enable.
<script language=javascript>

function WriteToile()

{ 

    var fso = new ActiveXObject("Scripting.FileSystemObject");

    var fileOpen = fso.OpenTextFile("c:\\test.txt",2,true); // Open the file for writing

    fileOpen.WriteLine("Some Text added");

    fileOpen.Close();  

}

function ReadTextFile()

{

    var fso = new ActiveXObject("Scripting.FileSystemObject");

    var fileOpen = fso.OpenTextFile("c:\\test.txt",1,true); // Open the file for writing

    var filecontent = fileOpen.ReadLine();

    alert(filecontent);

    fileOpen.Close();

}

</script>


Note:The “Initialize and Script ActiveX controls not marked as safe” option should be selected as “Enable”.Goto Tool Menu in browser ->Internet Option ->Security -> select Local intranet -> Click Custom Level ->go to "Initialize and Script ActiveX controls not marked as safe" and mark as enable


Thanks

Labels: