Wednesday 30 January 2013

Enable/Disable textbox on checkbox click using javascript


//------------- Javascript ----------------------

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

function CheckCheckboxes1(chk){
 
    if(chk.checked == true)
    {
        var txt = document.getElementById('TextBox1');
        txt.value = "";
        txt.disabled = false;
    }
    else
    {
        var txt = document.getElementById('TextBox1');
        txt.value = "Enter Username";
        txt.disabled = true;
    }

    OR

   //--------If you are working with master page then use following code to do the same

  //------ Disable textbox
  $("[id$='TextBox1']").prop('disabled',true);

  //------ Enable textbox
  $("[id$='TextBox1']").prop('disabled',false);

  OR
  //------ Disable textbox
  $("[id$='TextBox1']").attr("disabled", "disabled");

  //------ Enable textbox
  $("[id$='TextBox1']").removeAttr("disabled");

}
</script>

//------------- HTML ----------------------

<asp:CheckBox ID="chk_NetBanking" runat="server" onclick="CheckCheckboxes1(this)" /> <br /> <asp:TextBox ID="TextBox1" runat="server" Width="250px" Enabled="false" Text="Enter Username" MaxLength= "20"></asp:TextBox>

Groupbox in asp.net


<div>
                                                <fieldset style="border: 1px solid #cdcdcd; border-radius: 15px;">
                                                    <legend><span style="font-family: Felix Titling; font-size: 14pt; color: #2319b3;">&nbsp;Title Here&nbsp;</span></legend>
                                                   
                                                        <asp:TextBox ID="TextBox1" runat="server" Width="250px"     MaxLength="40"></asp:TextBox>   

//------------- your other controls..............
                                                               
                                                </fieldset>
                                                </div>

Saturday 26 January 2013

Setting default profile image if there is no database image available

.aspx page

<asp:Image ID="imb_ProfilePhoto" runat="server" Width="100px" Height="100px"  ImageUrl="~/images/user_profile.gif" />

// if you want to use html img tag instead of asp:image control then put this


<html>
    <body>
        <img src="<dynamic handler url>" alt="My Username" onError="this.src='../../images/user_profile.gif';" />
    </body>
</html>


Make ShowImage.ashx file and write this code


<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Web;
using System.IO;

public class ShowImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        Int32 empno = 0;

        if (context.Request.QueryString["id"] != null )
            empno = Convert.ToInt32(context.Request.QueryString["id"]);

     
        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowEmpImage(empno);
        byte[] buffer = new byte[4096];

        if (strm != null)
        {

            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
        }
        //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
        Class1 obj = new Class1();
        object objImg = obj.FetchPhoto(empno);

       // Here fetch your image from database, i used my class method for the same...

        try
        {
            return new MemoryStream((byte[])objImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            obj = null;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}


To assign default value if there is no database image value available.


imb_ProfilePhoto.ImageUrl = "ShowImage.ashx?id=" + id ;

imb_ProfilePhoto.Attributes["onError"] = "this.onerror=null;this.src='../../images/user_profile.gif';";

in src set your default image url to display.


Enjoy................

Working with ajax CascadingDropDown with C#

.aspx page

<table>

<tr>
                                        <td align="right" valign="top" style="width: 40%;">
                                            Select Country&nbsp;<span style="color:Red;">*</span>
                                        </td>
                                        <td align="center" valign="top">
                                            :
                                        </td>
                                        <td align="left" valign="top" style="width: 58%;">
                                            <asp:DropDownList ID="ddl_countryPermenent" runat="server" Width="250px" DataTextField="countryName" DataValueField="countryID">
                                             
                                            </asp:DropDownList>
                                            <cc1:CascadingDropDown ID="ccd_countryPermenent" runat="server" Category="Country"
                                                TargetControlID="ddl_countryPermenent" PromptText="Select Country" LoadingText="Loading country..."
                                                ServiceMethod="BindCountryDetails" ServicePath="WebService.asmx">
                                            </cc1:CascadingDropDown>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right" valign="top" style="width: 40%;">
                                            Select State&nbsp;<span style="color:Red;">*</span>
                                        </td>
                                        <td align="center" valign="top">
                                            :
                                        </td>
                                        <td align="left" valign="top" style="width: 58%;">
                                            <asp:DropDownList ID="ddl_statePermenent" runat="server" Width="250px">
                                             
                                            </asp:DropDownList>
                                            <cc1:CascadingDropDown ID="ccd_statePermenent" runat="server" Category="State" ParentControlID="ddl_countryPermenent"
                                                TargetControlID="ddl_statePermenent" PromptText="Select State" LoadingText="Loading state..."
                                                ServiceMethod="BindStateDetails" ServicePath="WebService.asmx">
                                            </cc1:CascadingDropDown>
                                        </td>
                                    </tr>
</table>


Now make one class file and create a method which calls store procedure


public DataSet RetiveCountry()
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ssp_SELECTCOUNTRY4DDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }




public DataSet RetiveState(int id)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("SSP_FETCHSTATEDDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }


Now make Http Handler file (.asmx)




using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;



/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
 
    //------ METHOD TO POPULATE COUNTRY -------------

    [WebMethod]
    public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues, string category)
    {
        ManageState obj = new ManageState();

        System.Data.DataSet ds = obj.RetiveCountry();

        System.Collections.Generic.List<CascadingDropDownNameValue> CountryDetails = new System.Collections.Generic.List<CascadingDropDownNameValue>();
        foreach (System.Data.DataRow dtrow in ds.Tables[0].Rows)
        {
            string CountryID = dtrow["countryID"].ToString();
            string CountryName = dtrow["countryName"].ToString();
            CountryDetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
        }
        obj = null;
        return CountryDetails.ToArray();
    }

    //------ METHOD TO POPULATE STATE -------------

    [WebMethod]
    public CascadingDropDownNameValue[] BindStateDetails(string knownCategoryValues, string category)
    {
        int countryID;
        //This method will return a StringDictionary containing the name/value pairs of the currently selected values
        StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        countryID = Convert.ToInt32(countrydetails["Country"]);
     
        //concountry.Open();
        //SqlCommand cmdstate = new SqlCommand("select * from StateTable where CountryID=@CountryID", concountry);
        //cmdstate.Parameters.AddWithValue("@CountryID", countryID);
        //cmdstate.ExecuteNonQuery();
        //SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);

        ManageState obj = new ManageState();

        DataSet dsstate = obj.RetiveState(countryID);
     
        //dastate.Fill(dsstate);
        //concountry.Close();

        //create list and add items in it by looping through dataset table
        List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dsstate.Tables[0].Rows)
        {
            string StateID = dtrow["stateId"].ToString();
            string StateName = dtrow["stateName"].ToString();
            statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
        }
        return statedetails.ToArray();
    }
}


Now access the dropdownlist value from code behind ( C# )



string countryP = ddl_countryPermenent.SelectedItem.Text;
        string stateP = ddl_statePermenent.SelectedItem.Text;


if (!string.IsNullOrEmpty(countryP)
{
            if (!string.IsNullOrEmpty(stateP))
           {
                        int id_country = Convert.ToInt32(ddl_countryPermenent.SelectedValue);
                        int id_state = Convert.ToInt32(ddl_statePermenent.SelectedValue);
            }
}


        string country_C = ddl_countryCurrent.SelectedItem.Text;
        string state_C = ddl_stateCurrent.SelectedItem.Text;


        int countryC = 0;
        int stateC = 0;
        if (!string.IsNullOrEmpty(country_C))
        {
            countryC = Convert.ToInt32(ddl_countryCurrent.SelectedValue);

            if (!string.IsNullOrEmpty(country_C))
            {
                stateC = Convert.ToInt32(ddl_stateCurrent.SelectedValue);
            }
        }



Now if you want to assign value from code behind then 


ccd_countryPermenent.SelectedValue = "your value from database OR your static value";
ccd_statePermenent.SelectedValue = "your value from database OR your static value";



Enjoy............ Best of luck

Declare null variable in C#



int? myInt = null;
bool? myBool = null;

You can declare any type of variable like mentioned above.


example : 


using System;
class MyPoint
{
static void Main()
{
int? myInt = null;
bool? myBool = null;
float? myFloat = 1.23F;
char? myChar = 'C';


Console.WriteLine("myInt = {0}\n"+
"myBool = {1}\n" +
"myFloat = {2}\n" +
"myChar = {3}\n",
myInt, myBool, myFloat, myChar);
}
}

Output:
myInt =
myBool =
myFloat = 1.23
myChar = C


Enjoy.................

Wednesday 23 January 2013

set value of label using javascript

<script type="text/javascript">
function SetValue() {
document.getElementById("lbl_msgAdd").innerHTML = "this is lable value";
}
</script>

<asp:Label ID="lbl_msgAdd" runat="server" ></asp:Label>