Monday 12 November 2012

finding the values inside the nested gridview Using Javascript / (using rowindex to find the nested gridview)/ (finding the selected rowindex of gridview on mouse click on the gridview row)



In Design Page

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

//get the row index and client id ,cell value
function showClickPage(rowid,id,selectedid)
{
 
var billamt=0;
var admissibleamt=0;
var nonadmissibleamt=0;
var billamt_tot=0;
var admissibleamt_tot=0;
var nonadmissibleamt_tot=0;
 var gridView1 = document.getElementById('<%=GVBillDetails.ClientID %>');
 var idExt=rowid ;
     if(parseInt(idExt,10) <= 9)
     {
         idExt = "0" + idExt ;               
     }           
     var VExtGrid = "GVBillDetails_ctl"+idExt;       
     var gridView = document.getElementById(VExtGrid+"_GVBillDetails1");
     for (var i = 1; i < gridView.rows.length - 1; i++)
     {
        var inputs1 = gridView.rows[i].getElementsByTagName('input')[0];
          if (inputs1.value.length<1)
          {
           nonadmissibleamt=0;
          }
         else
          {
           nonadmissibleamt =parseFloat(inputs1.value);
          }
       nonadmissibleamt_tot = nonadmissibleamt_tot +   nonadmissibleamt;
     }
      gridView.rows[gridView.rows.length - 1].getElementsByTagName('input')[0].value = nonadmissibleamt_tot;
      for (var i = 1; i < gridView.rows.length - 1; i++)
     {
        var inputs2 = gridView.rows[i].getElementsByTagName('input')[1];
          
          if (inputs1.value.length<1)
          {
           admissibleamt=0;
          }
         else
          {
           admissibleamt =parseFloat(inputs2.value);
          }
       admissibleamt_tot = admissibleamt_tot +   admissibleamt;
     }
      gridView.rows[gridView.rows.length - 1].getElementsByTagName('input')[1].value = admissibleamt_tot;  
}
</script>


in code behind:


 protected void GvBilldeatails_OnRowCreated(object sender, GridViewRowEventArgs e)
    {
       /// Gridview index will starts with  -1 so we are adding 2 to the current index here
       /// call the javscript function with 3 parameters as we are passing here



        int index = e.Row.RowIndex + 2;

        e.Row.Attributes.Add("onclick", "showClickPage('" + index + "','" + e.Row.ClientID + "','" + e.Row.Cells[0].Text + "');");

    }

-------------------------


or another method


You can attach an mouse over event handler to the rows of the grid in the OnRowDataBound event handler:

C#:
protected void OnGridRowDataBound(object sender, GridRowEventArgs args)
{
        args.Row.Attributes["onmouseover"] = "handleMouseOver(" + args.Row.RowIndex.ToString() + ")";
        ...
}

JavaScript:
<script type="text/javascript">
        function handleMouseOver(rowIndex) {
                alert('mouse over: ' + rowIndex);
        }

///after finding rowindex here same as above javscript we need to fallow

</script>

Tuesday 16 October 2012

Instead of default button click on page load, we can call any other particular button click

Instead of default button click on page load, we can call any other particular button click

In design page:

<script language="javascript" type="text/javascript"> 
 
        function clickButton(e, buttonid){  
 
          var evt = e ? e : window.event; 
 
          var bt = document.getElementById(
buttonid); 
 
          if (bt){  
 
              if (evt.keyCode == 13){  
 
                    bt.click();  
 
                    return false;  
 
              }  
 
          }  
 
        } 
 
    </script>


in Code behind:
    

    if (!IsPostBack)
         {
           
                 Textsearch.Attributes.Add("onkeypress", "return clickButton(event,'" + Btnsearch.ClientID + "')"); 
          
         }


Here after any keypress in the text seach box it will take to the search button click instead of default button
 
--------------------------------------------------------------------------
or
 
In form tag only we can set the Default focus and default button for a form as below
 
   <form id="form1" runat="server" defaultfocus="Textsearch" defaultbutton="Btnsearch">
 
 It will take given controls on page load...
 
 
 

Sunday 23 September 2012

Converting string to date format in C#



                                LBLDate.Text = authorizationInfo["authorizedtime1"].ToString();

                                string date1 = LBLDate.Text.ToString();

                                DateTime date = DateTime.Parse(date1);

                                string newdate = string.Format("{0:dddd ,MMM dd ,yyyy}", date);

                                LBLDate.Text = newdate.ToString();


    

Output:  
   
     Friday ,Sep 21 ,2012

Wednesday 25 July 2012

How to select values from a datatable based on the condition

// here 'm datatable from cache which is already stored, u can careate ur own datatable  
              
               string district = e.Row.Cells[0].Text.ToString();

                string cachekey = "PPNPreauthDistrictMIS_" + Session.SessionID;
                DataTable NewGdt = (DataTable)HttpRuntime.Cache[cachekey];

                DataRow[] rows = NewGdt.Select("DISTRICT = '" + district + "'");


                 dt = new DataTable();
                dt.Columns.Add("SL No");
                dt.Columns.Add("DISTRICT");
                dt.Columns.Add("PKG_CATEGORY");
                dt.Columns.Add("CASES");
                dt.Columns.Add("AMT");
                dt.Columns.Add("TOTALAPPAMOUNT");

                foreach (DataRow dr in rows)
                {

                    object[] row = dr.ItemArray;

                    dt.Rows.Add(row);

                    casesum = casesum + Convert.ToInt32(dr["CASES"]);
                    pratesum = pratesum + Convert.ToInt32(dr["AMT"]);
                    appamtsum = appamtsum + Convert.ToInt32(dr["TOTALAPPAMOUNT"]);
                }

                DataRow newrow = dt.NewRow();

                newrow["PKG_CATEGORY"] = "Total";
                newrow["CASES"] = casesum.ToString();
                newrow["AMT"] = pratesum.ToString();
                newrow["TOTALAPPAMOUNT"] = appamtsum.ToString();
                dt.Rows.Add(newrow);
                ChildGridview.DataSource = dt;
                ChildGridview.DataBind();
                int count = ChildGridview.Rows.Count;
                ChildGridview.Rows[count - 1].Font.Bold = true;





Caluclating the sum of all the rows in a datatable and place it in the last row

  // here 'm datatable from cache which is already stored, u can careate ur own datatable    

                DataTable NewGdt = (DataTable)HttpRuntime.Cache[cachekey];

                int casesum = 0;
                int pratesum = 0;
                int appamtsum = 0;
                DataTable dt = null;

                DataTable StatusDT = null;
                OleDbCommand cmd = null;
                OleDbDataAdapter StatusAdpt = null;

                DataRow[] rows = NewGdt.Rows;

                dt = new DataTable();
                dt.Columns.Add("SL No");
                dt.Columns.Add("DISTRICT");
                dt.Columns.Add("PKG_CATEGORY");
                dt.Columns.Add("CASES");
                dt.Columns.Add("AMT");
                dt.Columns.Add("TOTALAPPAMOUNT");

                foreach (DataRow dr in rows)
                {

                    object[] row = dr.ItemArray;

                    dt.Rows.Add(row);

                   // here 'm getting sum on each row

                    casesum = casesum + Convert.ToInt32(dr["CASES"]);
                    pratesum = pratesum + Convert.ToInt32(dr["AMT"]);
                    appamtsum = appamtsum + Convert.ToInt32(dr["TOTALAPPAMOUNT"]);
                }

                DataRow newrow = dt.NewRow();

                newrow["PKG_CATEGORY"] = "Total";
                newrow["CASES"] = casesum.ToString();
                newrow["AMT"] = pratesum.ToString();
                newrow["TOTALAPPAMOUNT"] = appamtsum.ToString();
                dt.Rows.Add(newrow);

                /// 'm binding final table to gridview

                ChildGridview.DataSource = dt;
                ChildGridview.DataBind();
                int count = ChildGridview.Rows.Count;
                ChildGridview.Rows[count - 1].Font.Bold = true;

How to select a distinct values from particular column in the datatable

// here 'm datatable from cache which is already stored, u can careate ur own datatable  

                    DataTable NewGdt = (DataTable)HttpRuntime.Cache[cachekey];
                    DataView Griddataview = new DataView(NewGdt);


                    DataTable distinctValues = Griddataview.ToTable(true, "Columnname");

How to implement Nested Gridview (Gridview within a gridview)



In Design page:

 <asp:GridView CssClass="content" ID="GVDistrict" runat="server" Width="100%" HorizontalAlign="Left" DataKeyNames="DISTRICT"
 AutoGenerateColumns="False" CaptionAlign="Left" OnRowDataBound="GVDistrict_OnRowDataBound"   >
 <Columns>
 <asp:BoundField DataField="DISTRICT" HeaderText="District">
     <HeaderStyle Width="12%" />
 </asp:BoundField>
   <asp:TemplateField HeaderText="Category Details">
 <ItemTemplate>

 <asp:GridView CssClass="content" ID="CategoryDeatils" runat="server" Width="100%" CaptionAlign="Left"
  AutoGenerateColumns="False" AllowSorting="True" HorizontalAlign="Left" >
  <columns>
   <asp:BoundField Datafield="PKG_CATEGORY" HeaderText="Category" />
    <asp:BoundField Datafield="CASES" HeaderText="#Cases" />
     <asp:BoundField Datafield="AMT" HeaderText="Package Amt." />     
    <asp:BoundField Datafield="TOTALAPPAMOUNT" HeaderText="Total App. Amt."/>
  </columns>
  <HeaderStyle CssClass="headerContent" HorizontalAlign="Left" />
 <AlternatingRowStyle HorizontalAlign="Left" BackColor="GhostWhite" />
 </asp:GridView>


 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 <HeaderStyle CssClass="headerContent" HorizontalAlign="Left" />
 <AlternatingRowStyle HorizontalAlign="Left" BackColor="GhostWhite" />
 </asp:GridView>




In code behind:

protected void bindparentgridview()

            
    {       

                  try
                  {

                    // Get some data in datatable and bind it to parent gridview


                    GVDistrict.DataSource = Gdt;
                    GVDistrict.DataBind();
                  }
                   
                
                   catch (HttpException ex)
                 {
                   Lblmsg.Text = "There seems to be problem in Network Connectivity. Please try again." + ex.ToString();
                 }
                   catch (Exception ex)
                 {
                   Lblmsg.Text = "There seems to be an Exception.  !!" + ex.ToString();
                 }

             
    }




 protected void GVDistrict_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {



        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           
           // get childgridview control here

           GridView ChildGridview = ((GridView)e.Row.FindControl("CategoryDeatils"));


          
            try
            {

              // get some datatable dt and bind the childgridview here

               
                ChildGridview.DataSource = dt;
                ChildGridview.DataBind();


            }
            catch (HttpException ex)
            {
                Lblmsg.Text = "There seems to be problem in Network Connectivity. Please try again." +    ex.ToString();
            }
            catch (Exception ex)
            {
                Lblmsg.Text = "There seems to be an Exception.  !!" + ex.ToString();
            }


        }

    }



Monday 2 July 2012

How to get only valid dates from a varchar date field in oracle





First we need to create a function as below:


CREATE OR REPLACE FUNCTION MY2DATE (p_str IN VARCHAR2
  ,format_picture IN VARCHAR2
)
   RETURN DATE
IS
BEGIN
   RETURN TO_DATE(p_str, format_picture);
EXCEPTION
   WHEN OTHERS
   THEN
      RETURN NULL;
END;




Call that function with field name and the valid date format while selecting:

SELECT MY2DATE(FIRST,'dd/mm/YYYY HH:MM AM') FROM ORDERS

Thursday 28 June 2012

Comparing Date between Two dates


Example: to_date(AUTHORIZEDTIME,'mm/dd/YYYY HH12:MI:SS AM') between to_date('" + fromdate + "','dd/mm/yyyy') and to_date('" + tilldate + "','dd/mm/yyyy') ORDER BY dateorder DESC


Syntax: to_date(Fieldname,'Date Format')  between to_date(Fieldname,'Date Format') and to_date(Fieldname,'Date Format')

Wednesday 20 June 2012

For checking all the rows in a gridview to check for already existing Identical values

int rowindex = GVRules.SelectedIndex;
        foreach (GridViewRow gvrow in GVRules.Rows)
        {
            if (gvrow.RowIndex != rowindex)
            {
                if (DdlRule.SelectedValue == GVRules.DataKeys[gvrow.RowIndex].Values[2].ToString()

&& DdlMemPrmZone.SelectedItem.Text == gvrow.Cells[2].Text && DdlMemProvZone.SelectedItem.Text ==

gvrow.Cells[3].Text)
                {
                    Label1.Text = "Rule " + DdlRule.SelectedItem.Text + " for Member Premium Zone "

+ DdlMemPrmZone.SelectedItem.Text + " and Member Provider Zone " + DdlMemProvZone.SelectedItem.Text

+ " is already added to this Policy !!";
                    return false;
                }
            }

        }

Sorting the gridview column wise, using datasource

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for AutowithholdruleforDS
/// </summary>
public class AutowithholdruleforDS
{
    public AutowithholdruleforDS()
    {
        string Cachekey = "AutowithholdRule_" + HttpContext.Current.Session.SessionID;
         this.CD1 = (DataTable)HttpRuntime.Cache[Cachekey];
    }
    private DataTable CD1;

    public DataView Select()
    {
        if (this.CD1 != null)
        {
            this.CD1.DefaultView.Sort = "";
            return this.CD1.DefaultView;
        }
        else
        {
            return null;
        }
    }
}

Email validation using Javascript

function EmailValidCheck(emailtxt)
{
 var email1=document.getElementById(emailtxt).value;
 var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
 if(email1.length>0)
 {
 var returnval=emailfilter.test(email1);
 if (returnval==false)
 {
 alert("Please Enter Valid Employee Email ID !!")
 document.getElementById(emailtxt).focus();
 return false;
 }
 }
}

Thursday 24 May 2012

Adding Two text box value and redirecting it to third text box value

In design Page


 <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server" OnTextChanged="text2_changed" AutoPostBack="true"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    </div>
    </form>

In code behind


    protected void text2_changed(object sender, EventArgs e)
    {
        try
        {

            int x = Convert.ToInt32(TextBox1.Text);
            int y = Convert.ToInt32(TextBox2.Text);

            int z = x + y;

            TextBox3.Text = z.ToString();
        }
        catch (Exception ex)
        {
            Label1.Text = "There seems to be an Exception.  !!" + ex.ToString();
        }
    }





Wednesday 2 May 2012

format for inner join SQL query

select columns
from table t1
inner join table t2 on t1.column1 = t2.column2
inner join table t3 on t1.column1 = t2.column2
where condition


example:

"Select a.ENTITYCODE,QUERYTYPEAFFID,b.tpaname,REQUESTTYPE,STATUS,QUERYTYPE from  STATUS_QUERY_TYPE_AFF a LEFT OUTER JOIN mastertpa b ON a.ENTITYCODE = b.TPACODE where a.ENTITYCODE=?"

Monday 23 April 2012

Simple way to do the Paging in gridview

In aspx page:


 <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="true" PagerSettings-Mode="Numeric" PagerSettings-Position="TopAndBottom" PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" >
       
        </asp:GridView>
    </div>
    </form>

In code behind:


protected void Page_Load(object sender, EventArgs e)
    {


        adddata();
    }


//Binding gridview


    public void adddata()
    {


        conn.Open();

        string strSQL = "Select * from LOGINDETAILS";

        OleDbCommand cmd = new OleDbCommand(strSQL, conn);

        DataSet ds = new DataSet();

        OleDbDataAdapter da = new OleDbDataAdapter(cmd);

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();
        conn.Close();

    }


//paging index


    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)          
    {
        GridView1.PageIndex = e.NewPageIndex;
        adddata();
    }



output:


Biniding Gridview in asp .net

public void adddata()
    {


        conn.Open();

        string strSQL = "Select * from LOGINDETAILS";

        OleDbCommand cmd = new OleDbCommand(strSQL, conn);

        DataSet ds = new DataSet();

        OleDbDataAdapter da = new OleDbDataAdapter(cmd);

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }


Call this method in pageload.....
Thats it.......

Sunday 22 April 2012

Coding structure that we use in Progamming Languages

With PascalCase, the first letter of every word in the identifier is upper case.

With camelCase, the first letter of the first word in the identifier is lower case, while the first letter of every subsequent word is uppercase.






Happy coding....... !!!!!

Friday 13 April 2012

converting numeric values into words

In design part:

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server" Width="350px" ></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>

In code behind:

public partial class _Default : System.Web.UI.Page
{
    string Number;
    string deciml;
    string _number;
    string _deciml;
    string[] US = new string[1003];
    string[] SNu = new string[20];
    string[] SNt = new string[10];
    protected void Page_Load(object sender, EventArgs e)
    {
        Initialize();
    }

 
    protected void Button1_Click(object sender, EventArgs e)
    {
        string currency = "Rupees ";
        string _currency = " Paise Only";
        if (Convert.ToDouble(TextBox1.Text) == 0)
        {
            TextBox2.Text = "Null Value";
            return;
        }
        if (Convert.ToDouble(TextBox1.Text) < 0)
        {
            TextBox2.Text = "Invalid Value";
            return;
        }
        string[] no = TextBox1.Text.Split('.');
        if ((no[0] != null) && (no[1] != "00"))
        {
            Number = no[0];
            deciml = no[1];
            _number = (NameOfNumber(Number));
            _deciml = (NameOfNumber(deciml));
            TextBox2.Text = currency + _number.Trim() + " and " + _deciml.Trim() + _currency;
        }
        if ((no[0] != null) && (no[1] == "00"))
        {
            Number = no[0];
            _number = (NameOfNumber(Number));
            TextBox2.Text = currency + _number + "Only";
        }
        if ((Convert.ToDouble(no[0]) == 0) && (no[1] != null))
        {
            deciml = no[1];
            _deciml = (NameOfNumber(deciml));
            TextBox2.Text = _deciml + _currency;
        }

     
    }

    public string NameOfNumber(string Number)
    {
        string GroupName = "";
        string OutPut = "";

        if ((Number.Length % 3) != 0)
        {
            Number = Number.PadLeft((Number.Length + (3 - (Number.Length % 3))), '0');
        }
        string[] Array = new string[Number.Length / 3];
        Int16 Element = -1;
        Int32 DisplayCount = -1;
        bool LimitGroupsShowAll = false;
        int LimitGroups = 0;
        bool GroupToWords = true;
        for (Int16 Count = 0; Count <= Number.Length - 3; Count += 3)
        {
            Element += 1;
            Array[Element] = Number.Substring(Count, 3);

        }
        if (LimitGroups == 0)
        {
            LimitGroupsShowAll = true;
        }
        for (Int16 Count = 0; (Count <= ((Number.Length / 3) - 1)); Count++)
        {
            DisplayCount++;
            if (((DisplayCount < LimitGroups) || LimitGroupsShowAll))
            {
                if (Array[Count] == "000") continue;
                {
                    GroupName = US[((Number.Length / 3) - 1) - Count + 1];
                }


                if ((GroupToWords == true))
                {
                    OutPut += Group(Array[Count]).TrimEnd(' ') + " " + GroupName + " ";

                }
                else
                {
                    OutPut += Array[Count].TrimStart('0') + " " + GroupName;

                }
            }

        }
        Array = null;
        return OutPut;

    }

    private string Group(string Argument)
    {
        string Hyphen = "";
        string OutPut = "";
        Int16 d1 = Convert.ToInt16(Argument.Substring(0, 1));
        Int16 d2 = Convert.ToInt16(Argument.Substring(1, 1));
        Int16 d3 = Convert.ToInt16(Argument.Substring(2, 1));
        if ((d1 >= 1))
        {
            OutPut += SNu[d1] + " hundred ";
        }
        if ((double.Parse(Argument.Substring(1, 2)) < 20))
        {
            OutPut += SNu[Convert.ToInt16(Argument.Substring(1, 2))];
        }
        if ((double.Parse(Argument.Substring(1, 2)) >= 20))
        {
            if (Convert.ToInt16(Argument.Substring(2, 1)) == 0)
            {
                Hyphen += " ";
            }
            else
            {
                Hyphen += " ";
            }
            OutPut += SNt[d2] + Hyphen + SNu[d3];
        }
        return OutPut;
    }

    private void Initialize()
    {

        SNu[0] = "";
        SNu[1] = "One";
        SNu[2] = "Two";
        SNu[3] = "Three";
        SNu[4] = "Four";
        SNu[5] = "Five";
        SNu[6] = "Six";
        SNu[7] = "Seven";
        SNu[8] = "Eight";
        SNu[9] = "Nine";
        SNu[10] = "Ten";
        SNu[11] = "Eleven";
        SNu[12] = "Twelve";
        SNu[13] = "Thirteen";
        SNu[14] = "Fourteen";
        SNu[15] = "Fifteen";
        SNu[16] = "Sixteen";
        SNu[17] = "Seventeen";
        SNu[18] = "Eighteen";
        SNu[19] = "Nineteen";
        SNt[2] = "Twenty";
        SNt[3] = "Thirty";
        SNt[4] = "Forty";
        SNt[5] = "Fifty";
        SNt[6] = "Sixty";
        SNt[7] = "Seventy";
        SNt[8] = "Eighty";
        SNt[9] = "Ninety";
        US[1] = "";
        US[2] = "Thousand";
        US[3] = "Million";
        US[4] = "Billion";
        US[5] = "Trillion";
        US[6] = "Quadrillion";
        US[7] = "Quintillion";
        US[8] = "Sextillion";
        US[9] = "Septillion";
        US[10] = "Octillion";
    }
}


Output:




Thursday 29 March 2012

simple and easy form validation using HTML 5 attribute



<table>
<tr>
    <td class="style1">
      <div align="left">Title<sup>*</sup></div>
    </td>
    <td>
      <div align="left">
          <asp:TextBox ID="TextBox1" runat="server"  required="required" ></asp:TextBox>
   
        </div>
    </td>
  </tr>

 <tr>
    <td class="style1">
      <div align="left"> Price<sup>*</sup>   </div>
    </td>
    <td>
      <div align="left"> <asp:TextBox ID="TextBox2" runat="server"  required="required"              pattern="[0-9]+$"  title="only numeric constants"></asp:TextBox></div>
    </td>
  </tr>
<tr>
<button runat="server"/>
</tr>

---------------------------------------------------------------------------------
thats it..................


we need use required="required' attribte of html5
and if we need to validate for specific constraint use pattern attribute just like regular expression validator
just like above second condition

<table>

Tuesday 27 March 2012

List of all the states which may be usefull in register form to list out our states


Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya pradesh
Maharashtra
Manipur
Megalaya
Mizoram
Nagaland
Orissa
Punjab
Rajashthan
Sikkim
Tamil Nadu
Tripura
Uttar Pradesh
Uttarakhand
West Bengal

Monday 26 March 2012

List of all the countries which may be usefull in register form to list out countries


Afghanistan
Akrotiri
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Ashmore and Cartier Islands
Australia
Austria
Azerbaijan
Bahamas, The
Bahrain
Bangladesh
Barbados
Bassas da India
Belarus
Belgium
Belize
Benin
Bermuda
Bhutan
Bolivia
Bosnia and Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
British Virgin Islands
Brunei
Bulgaria
Burkina Faso
Burma
Burundi
Cambodia
Cameroon
Canada
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Clipperton Island
Cocos (Keeling) Islands
Colombia
Comoros
Congo, Democratic Republic of the
Congo, Republic of the
Cook Islands
Coral Sea Islands
Costa Rica
Cote d'Ivoire
Croatia
Cuba
Cyprus
Czech Republic
Denmark
Dhekelia
Djibouti
Dominica
Dominican Republic
Ecuador
Egypt
Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Europa Island
Falkland Islands
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern and Antarctic Lands
Gabon
Gambia, The
Gaza Strip
Georgia
Germany
Ghana
Gibraltar
Glorioso Islands
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard Island and McDonald Islands
Holy See (Vatican City)
Honduras
Hong Kong
Hungary
Iceland
India
Indonesia
Iran
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jan Mayen
Japan
Jersey
Jordan
Juan de Nova Island
Kazakhstan
Kenya
Kiribati
Korea, North
Korea, South
Kuwait
Kyrgyzstan
Laos
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States of
Moldova
Monaco
Mongolia
Montserrat
Morocco
Mozambique
Namibia
Nauru
Navassa Island
Nepal
Netherlands
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Norway
Oman
Pakistan
Palau
Panama
Papua New Guinea
Paracel Islands
Paraguay
Peru
Philippines
Pitcairn Islands
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russia
Rwanda
Saint Helena
Saint Kitts and Nevis
Saint Lucia
Saint Pierre and Miquelon
Saint Vincent and the Grenadines
Samoa
San Marino
Sao Tome and Principe
Saudi Arabia
Senegal
Serbia and Montenegro
Seychelles
Sierra Leone
Singapore
Slovakia
Slovenia
Solomon Islands
Somalia
South Africa
South Georgia and the South Sandwich Islands
Spain
Spratly Islands
Sri Lanka
Sudan
Suriname
Svalbard
Swaziland
Sweden
Switzerland
Syria
Taiwan
Tajikistan
Tanzania
Thailand
Timor-Leste
Togo
Tokelau
Tonga
Trinidad and Tobago
Tromelin Island
Tunisia
Turkey
Turkmenistan
Turks and Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United Kingdom
United States
Uruguay
Uzbekistan
Vanuatu
Venezuela
Vietnam
Virgin Islands
Wake Island
Wallis and Futuna
West Bank
Western Sahara
Yemen
Zambia
Zimbabwe

Tuesday 13 March 2012

procedure to update the table values


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER procedure [dbo].[updating]
(
@regid int,
@name varchar(50),
@email varchar(50),
@password varchar(50),
@phno varchar(50),
@addres varchar(50),
@institute varchar(50),
@course varchar(50),
@studying varchar(50)
)
as
update registration set
SE_name = @name,
SE_email = @email,
SE_password = @password,
SE_phno = @phno,
SE_address = @addres,
SE_institute = @institute,
SE_course = @course,
SE_studying = @studying
where
SE_regid = @regid

Friday 9 March 2012

How to store and retrieve images into databse in binary format.

In design page

<div id="new" align="left">
<p><label>Name:</label>
    <asp:Image ID="Image1" runat="server"  ImageAlign="Right" ImageUrl="~/images/commentbox.gif"/></p>
<div style=" padding-left:15px;">
    <asp:TextBox ID="TextBox1" runat="server" Width="191px"></asp:TextBox></div>
<p align="left"><label>E-mail</label></p>
<div align="left" style=" padding-left:15px;">
    <asp:TextBox ID="TextBox2" runat="server" Width="191px"></asp:TextBox></div>
   
<p align="left"><label>Upload Profile Picture</label></p>
<div align="left" style=" padding-left:15px;">
    <asp:FileUpload ID="FileUpload1" runat="server" /></div>  
  <div>
<label align="left">Comments/queries</label></div>
<div id="selector" align="left">

    <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Height="80px"
        Width="585px"></asp:TextBox>
 
        </div>
             <div align="right" style="width: 71%">
    <asp:ImageButton ID="ImageButton1" runat="server" width="120px" Height="30"
        ImageUrl="~/images/comment.png" onclick="ImageButton1_Click"/>

       
       
        </div>
</div>
<br />
    <div>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label></div>
        ///// Inserting Into database
<div  id="selector2">
<br />
<asp:DataList ID="ddl1" runat="server" Width="620px"
        onitemcommand="ddl1_ItemCommand"
        onselectedindexchanged="ddl1_SelectedIndexChanged">
<ItemTemplate>
<div class="outr">
<table width="100%">
<tr><div style=" background-color:Maroon; padding-left:10px;"><asp:Label ID="name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_name") %>' Font-Bold="true" ForeColor="White" Font-Size="Small" ></asp:Label></div></tr>
<tr>
<td valign="top" width="20%"><asp:Image ID="Image1" runat="server" 
         ImageUrl='<%# "GetImage.aspx?id=" + Eval("SE_commentid") %>' width="100px" Height="100px" align="left" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px"/> 
         //// Please observe here 'm using image handler
         </td>
<td valign="top" width="80%"><div><asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_comment")%>' CssClass="expanding" AutoPostBack="false" TextMode="MultiLine" Width="100%" BorderStyle="None" style="resize:none;"></asp:TextBox></div></td>

</tr>
<tr> </tr>
</table>
    <asp:Button ID="hiddenbutton" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_commentid") %>' visible="false" />
<%--<div><textarea runat="server" text='<%# DataBinder.Eval(Container.DataItem, "SE_comment")%>'></textarea></div>--%>
<div style="padding-left:10px;" align="right">
 <font style=" font-size:small; font-weight:bold;">Posted date:</font><asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_posteddate") %>' Font-Bold="true" ForeColor="DarkOliveGreen" Font-Size="Small" ></asp:Label><asp:Label
    ID="Label3" runat="server" ></asp:Label></div>
 
</div>
<%-- <hr  width="100%" color="#EEE6E6"/>--%>
<br />

</ItemTemplate>
</asp:DataList>
    <asp:Label ID="Label5" runat="server" Visible="false"></asp:Label>
</div>      
////// Retreiving from database




In code behind


 protected void Page_Load(object sender, EventArgs e)
    {
        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection con = new SqlConnection(connstr);
        try
        {
           // SqlCommand cmd = new SqlCommand("select top 10 * from Commentbox order by SE_commentid Desc", con);

           // cmd.Connection.Open();

           //ddl1.DataSource = cmd.ExecuteReader();

           //ddl1.DataBind();

   
            string query = "select top 10 * from Commentbox order by SE_commentid Desc";
            SqlDataAdapter da = new SqlDataAdapter(query, con);
            DataTable table = new DataTable();

            da.Fill(table);
            ddl1.DataSource = table;
            ddl1.DataBind();

            //cmd.Connection.Close();
            //cmd.Connection.Dispose();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
       
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstr);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "dbo.comment";
   
        cmd.Parameters.AddWithValue("@name",TextBox1.Text);
        cmd.Parameters.AddWithValue("@email", TextBox2.Text);
        cmd.Parameters.AddWithValue("@comment", TextBox3.Text);
   

        if (FileUpload1.HasFile)
        {
            //getting length of uploaded file
            int length = FileUpload1.PostedFile.ContentLength;
            //create a byte array to store the binary image data
            byte[] imgbyte = new byte[length];
            //store the currently selected file in memeory
            HttpPostedFile img = FileUpload1.PostedFile;
            //set the binary data
            img.InputStream.Read(imgbyte, 0, length);
           // string imagename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
            //use the web.config to store the connection string

            //string newimagename = TextBox1.Text + imagename;

            // Session["imagepreserve"] = imgbyte;
            //con.Open();
            //SqlCommand cmd1 = new SqlCommand("SELECT  max(SE_Regcollid) FROM institutereg", con);

            //int res = (int)cmd1.ExecuteScalar();
            //int newres = (res + 1);
            //string newid = TextBox1.Text + newres;
            //con.Close();


            //  con.Open();

           /// cmd.Parameters.AddWithValue("@imagename", newimagename);
           ///
            cmd.Parameters.AddWithValue("@image", imgbyte);

            //  con.Close();

        }
        else
        {


            string filePath = Server.MapPath("~/images/nocommentimage.png");
            Byte[] imgByte = System.IO.File.ReadAllBytes(filePath);

          //  string newimagename = TextBox1.Text + "imagenotfound";
            //con.Open();
            //SqlCommand cmd1 = new SqlCommand("SELECT  max(SE_Regcollid) FROM institutereg", con);

            //int res = (int)cmd1.ExecuteScalar();
            //int newres = (res + 1);
            //string newid = TextBox1.Text + newres;
            //con.Close();


            cmd.Parameters.AddWithValue("@image", imgByte);


        }


        cmd.Connection = conn;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }

     
    }

    protected void ImageButton2_click(object sender, ImageClickEventArgs e)
    {
     
        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection con = new SqlConnection(connstr);
        string id = Request.QueryString["id"];

        SqlCommand cmd = new SqlCommand("SELECT SE_vote from Commentbox where SE_commentid = '" + id + " '", con);

       con.Open();

       Label5.Text = cmd.ExecuteScalar().ToString();

       con.Close();
       

     

    }

    protected void ddl1_ItemCommand(object source, DataListCommandEventArgs e)
    {

        if (e.CommandName == "view")
        {
            Button hb = (Button)(e.Item.FindControl("hiddenbutton"));
            Response.Redirect("comments.aspx?id=" + hb.Text);
        }

    }


In image handler

Just create the new page and save it as GetImage.aspx .




  protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["id"];

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString);
        string imageid = Request.QueryString["id"];

        con.Open();
        SqlCommand command = new SqlCommand("select SE_image from Commentbox where SE_commentid=" + imageid, con);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        Response.BinaryWrite((Byte[])dr[0]);
        con.Close();
        Response.End();
    }



thats it...................

Monday 5 March 2012

on mouseover changing the background color of the row in datalist


<style type="text/css">
   
    #divname {
background-color:white;
}
#divname:hover {
background-color:#dddddd;
}
</style>

--------------------------------------------------------------------------------------


<asp:DataList ID="DataList1" runat="server" Width="627px" >
    <ItemTemplate>
    <div id="divname">    /// use css style here
    <div id="div1" style="padding-left:5px;">
    <asp:Label ID="label1" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_collegename")%>' Font-Bold="true" ForeColor="#0099CC" Font-Size="Small" Font-Underline="true"></asp:Label>
    </div>
    <br />
    <div id="div2" style="padding-left:5px;">
    <asp:Label ID="label2" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_Loaction")%>' ></asp:Label>
    </div>
        <br />
   
    <div style="padding-left:5px;">
    <asp:Label ID="label3" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_category")%>' ></asp:Label>
   
    </div>
    <div id="div3" align="right" style="padding-right:5px;">
        <asp:LinkButton ID="LinkButton1" CommandName="view" runat="server">View more</asp:LinkButton>
    </div>
    </div>
    <hr  width="100%" color="#EEE6E6"/>
    <br />
    </ItemTemplate>
 
    </asp:DataList>




...................................................................

Thats it...............

Saturday 3 March 2012

stored procedure for searching records with if - else - condition


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[search1]
(
@category varchar(max),
@state varchar(max),
@City varchar(max)
)as
if @category = 'Select Category' and @state = '' and @City = ''
Begin
Select * From Colleges;
END

else if @state = '' and @City = ''
Begin
Select * From Colleges where SE_category =@category
END

else if @category = 'Select Category' and @City = ''
Begin
Select * From Colleges where SE_Loaction =@state
END

else if @category = 'Select Category' and @state = ''
Begin
Select * From Colleges where SE_Loaction =@City
END

else if @category = 'Select Category'
Begin
Select * From Colleges where SE_Loaction = @state or SE_Loaction =@City
END

else if @state = ''
Begin
Select * From Colleges where SE_category =@category  and SE_Loaction =@City
END

else if @City = ''
Begin
Select * From Colleges where SE_category =@category  and SE_Loaction =@state
END

else
Begin
Select * From Colleges where SE_category =@category  and SE_Loaction =@state and  SE_Loaction =@City
END

Friday 2 March 2012

grouping of list values in dropdownlist

1 First we need to add other third party .dll file

Koutny.WebControls.DropDownGroupableList.Net2.dll


2 Then we need to include this in our project

we do this by adding this Koutny.WebControls.DropDownGroupableList.Net2.dll file in bin and adding inleft side toolbox

3 after this include this in web config file


<authentication mode="Windows"/>
<pages>
<controls>
<add tagPrefix="koutny" namespace="Koutny.Web.UI.WebControls" assembly="Koutny.WebControls.DropDownGroupableList.Net2"/>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></controls>
<namespaces>
<add namespace="Koutny.Web.UI.WebControls"/>
</namespaces>
</pages>



4 after that use the control in design page like this


 <koutny:DropDownGroupableList ID="drop1" runat="server" CssClass="select" Width="150px" >
<koutny:OptionListItem Text="Select Category"/>
</koutny:DropDownGroupableList>

5 and in code behind


 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            drop1.Items.AddItem("Item1");
            drop1.Items.AddItem("Item2");
            drop1.Items.AddGroup("Group1", "G1");
            drop1.Items.AddItem("Item3", "Item3", "G1");
            drop1.Items.AddItem("Item4", "Item4", "G1");
            drop1.Items.AddItem("Item5");
        }
    }


6. to get the value of the selected item use like this

   protected void DisplaySelectedItem(object sender, EventArgs e)
{
OptionListItem selectedItem = drop1.SelectedItem;
if (selectedItem != null)
{
litSelectedItem.Text = selectedItem.Text;

OptionGroupItem selectedGroup = drop1.SelectedGroup;
if (selectedGroup != null) litSelectedGroup.Text = selectedGroup.Text;
else litSelectedGroup.Text = "none";
}
}


Thursday 1 March 2012

How to pass field value from one page to another page

Case: we need to send dropdownlist value which is in home page to search result page on button click


in button click include this
 
     Response.Redirect("Searchresults.aspx?DropDownList1=" + DropDownList1.SelectedItem.Text);

in serach result page access the value like this 

      String s = Request.QueryString["DropDownList1"];
       Label4.Text = s;


Thats it..........



DropDownList1 is the variable wch holds the value
DropDownList1.SelectedItem.Text is the property for the value.

Wednesday 22 February 2012

storing text documents in the folder and the file path in the database

1 .first create the folder to store the documents 
    here i created folder with name "documents"


2 after that create table in database like this


and in code behind

   string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
        //Save images into Images folder
        FileUpload1.SaveAs(Server.MapPath("documents/" + FileName));
        //Getting dbconnection from web.config connectionstring
     
        //Open the database connection
        con.Open();
        //Query to insert images path and name into database
        SqlCommand cmd = new SqlCommand("Insert into testing(ImageName,ImagePath) values(@ImageName,@ImagePath)", con);
        //Passing parameters to query
        cmd.Parameters.AddWithValue("@ImageName", FileName);
        cmd.Parameters.AddWithValue("@ImagePath", "documents/" + FileName);
        cmd.ExecuteNonQuery();
        //Close dbconnection
        con.Close();

Monday 20 February 2012

Procedure to bind checkboxlist control


  public void chkboxlist()
    {
        SqlDataAdapter da = new SqlDataAdapter("select SE_Category from category", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        CheckBoxList1.DataSource = dt;
        CheckBoxList1.DataTextField = "SE_Category";
        CheckBoxList1.DataValueField = "SE_Category";
        CheckBoxList1.DataBind();
        CheckBoxList1.Items.Insert(0, "Others");
    }


Thursday 9 February 2012

Importing data from text fles/notepad into database



BULK
INSERT table_name
FROM 'C:\Documents and Settings\manju\Desktop\test.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

Monday 6 February 2012

Most hardest thing is to change the default view of the DropDown LIst. here is the simple CSS for that


<style type="text/css"> 
.select {
  -webkit-appearance: button;
  -webkit-border-radius: 2px;
  -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
  -webkit-padding-end: 20px;
  -webkit-padding-start: 2px;
  -webkit-user-select: none;
  background-image: url(images/arrow.png),
    -webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
  background-position: center right;
  background-repeat: no-repeat;
  border: 1px solid #AAA;
  color: #555;
  font-size: inherit;
  margin: 0;
  overflow: hidden;
  padding-top: 2px;
  padding-bottom: 2px;
  text-overflow: ellipsis;
  white-space: nowrap;}
</style>
.----------------------------




  <asp:DropDownList ID="DropDownList1" runat="server"  CssClass="select"    Width="150px">
        <asp:ListItem>manja</asp:ListItem>
         <asp:ListItem>manja1</asp:ListItem>
          <asp:ListItem>manja2</asp:ListItem>
           <asp:ListItem>manja3</asp:ListItem>
        </asp:DropDownList>



    thats it .............. joy......

Sunday 22 January 2012

Simple method to send mails form your asp.net


first include

Using System.Net.Mail;

-------------------------------------------


protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.From = new MailAddress("manjunath.le@smartdrivelabs.com");
        mail.Subject = "Mail from manju";

        string Body = "Hi, this mail is manju ";
        mail.Body = Body;

        mail.IsBodyHtml = true;
     
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("your mail id", "password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = false;
        smtp.Send(mail);
    }

thats it........




Simple method to send mails form your asp.net with attachment


first include

Using System.Net.Mail;

-------------------------------------------


protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.From = new MailAddress("manjunath.le@smartdrivelabs.com");
        mail.Subject = "Mail from manju";

        string Body = "Hi, this mail is From Manju ";
        mail.Body = Body;

        mail.IsBodyHtml = true;
        if (FileUpload1.HasFile)
        {
            string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
        }


        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gamil.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("your mailid", "password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = false;
        smtp.Send(mail);
    }
thats it...............

your SMTP server name means......... the outgoing mail server for your mail id which ll be used in outlook for mail configuration


Wednesday 18 January 2012

stored procedure for inserting records

first create the procedure in the sql server like this

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[comment]
(
@name varchar(50),
@email varchar(50),
@comment varchar(max)
)
as
insert into Commentbox (SE_name,SE_Email,SE_comment) values (@name,@email,@comment)

and then in code behind

 string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstr);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "dbo.comment";
 
        cmd.Parameters.AddWithValue("@name",TextBox1.Text);
        cmd.Parameters.AddWithValue("@email", TextBox2.Text);
        cmd.Parameters.AddWithValue("@comment", TextBox3.Text);
        cmd.Connection = conn;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }

        TextBox3.Text = "";
        TextBox2.Text = "";
        TextBox1.Text = "";

Friday 13 January 2012

How to make datalist content to scroll from top


   <div id="js1" style="overflow:hidden; left:114px; top:600px; width:810px; height:300px; z-index:0">
   <div align="center" id="c_js1" style="overflow:hidden;height:100%;width:100%;">
     
    <div id="p1_js1">


/// your datalist code



<asp:DataList ID="DataList1" runat="server" Width="627px" >
    <ItemTemplate>
    <div id="selector2">
    <div id="div1" style="padding-left:5px;">
    <asp:Label ID="label1" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>' ForeColor="#0099CC" Font-Bold="true" Font-Size="Medium"></asp:Label>
    </div>
    <div id="div2" align="center">
    <asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>' Style="overflow: hidden;resize:none;" Height="30px" TextMode="MultiLine" Width="95%" MaxLength="100" BorderStyle="None" ></asp:TextBox>
    </div>
    <div id="div3" align="right" style="padding-right:5px;">
        <asp:LinkButton ID="LinkButton1" CommandName="view" runat="server">View more</asp:LinkButton>
    </div>
    </div>
    <asp:Button ID="hiddenbutton" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "SE_postid")%>' runat="server"/>
    <br />
    </ItemTemplate>
     <AlternatingItemStyle BackColor="White" />

    <ItemStyle BackColor="#FFFBD6" ForeColor="#333333"/>

    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 
    </asp:DataList>


 <br>
</div>
<div id="p2_js1"></div>
</div>



<script language="javascript" type="text/javascript">
var speed=30
var i=0
var n=Math.floor(js1.offsetHeight/p1_js1.offsetHeight)
for (i=0;i<=n;i++)
{
p2_js1.innerHTML+=p1_js1.innerHTML
}
function m_js1()
{
if(c_js1.scrollTop<=p1_js1.offsetTop)
c_js1.scrollTop+=p1_js1.offsetHeight
else{
c_js1.scrollTop--
}
}
var mm_js1=setInterval(m_js1,speed)
c_js1.onmouseover=function(){clearInterval(mm_js1)}
c_js1.onmouseout=function(){mm_js1=setInterval(m_js1,speed)}
</script></div>


thats it.........! it ll scroll the content of the datalist from top

Thursday 12 January 2012

Paging the datalist content with page numbers

your design page looks like this:



    <asp:Label ID="error" runat="server" Text=""></asp:Label>
<div id="selector1" style="font-family:Tahoma;
      font-size:15px;
      font-weight:bold">
 &nbsp;&nbsp;&nbsp;Events and Exhibitions
</div>
<div id="selector" align="center" >
    <div id="div5" align="right">
     Select number of events to be displayed per page<asp:DropDownList ID="ddlIndex" runat="server" AutoPostBack="True"
            onselectedindexchanged="ddlIndex_SelectedIndexChanged">
        </asp:DropDownList>
    </div>
    <asp:DataList ID="DataList1" runat="server" Width="627px" >
    <ItemTemplate>
    <div id="selector2">
    <div id="div1" style="padding-left:5px;">
    <asp:Label ID="label1" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>' ForeColor="#0099CC" Font-Bold="true" Font-Size="Medium"></asp:Label>
    </div>
    <div id="div2" align="center">
    <asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>' Style="overflow: hidden;resize:none;" Height="30px" TextMode="MultiLine" Width="95%" MaxLength="100" BorderStyle="None" ></asp:TextBox>
    </div>
    <div id="div3" align="right" style="padding-right:5px;">
        <asp:LinkButton ID="LinkButton1" CommandName="view" runat="server">View more</asp:LinkButton>
    </div>
    </div>
    <asp:Button ID="hiddenbutton" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "SE_postid")%>' runat="server"/>
    <br />
    </ItemTemplate>
     <AlternatingItemStyle BackColor="White" />

    <ItemStyle BackColor="#FFFBD6" ForeColor="#333333"/>

    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 
    </asp:DataList>
    <div id="div4" align="center">
  <table>
    <tr>
    <td colspan="5">  </td>
    </tr>
    <tr>
    <td width="80" valign="top" align="center"><asp:LinkButton ID="lnkFirst"
            runat="server" onclick="lnkFirst_Click">First</asp:LinkButton></td>
    <td width="80" valign="top" align="center"><asp:LinkButton ID="lnkPrevious"
            runat="server" onclick="lnkPrevious_Click">Previous</asp:LinkButton></td>
    <td>
            <asp:DataList ID="DataListPaging" runat="server" RepeatDirection="Horizontal"
                onitemcommand="DataListPaging_ItemCommand"
                onitemdatabound="DataListPaging_ItemDataBound">
            <ItemTemplate>
                <asp:LinkButton ID="Pagingbtn" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="newpage" Text='<%# Eval("PageText") %> '></asp:LinkButton>
            </ItemTemplate>
            </asp:DataList>
    </td>
    <td width="80" valign="top" align="center">
            <asp:LinkButton ID="lnkNext" runat="server" onclick="lnkNext_Click">Next</asp:LinkButton>
    </td>
    <td width="80" valign="top" align="center">
        <asp:LinkButton ID="lnkLast" runat="server" onclick="lnkLast_Click">Last</asp:LinkButton>
    </td>
    </tr>
    <tr>
    <td colspan="5" align="center"><asp:Label ID="lblpage" runat="server" Text=""></asp:Label></td></tr>
    </table>    
</div>

<%--<asp:DataList ID="DataList1" runat="server" Width="150px">
    <ItemTemplate>
<table width="200px" height="300px" border="1">
<tr>
<td> Eventname:<asp:Label ID="label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>'></asp:Label></td>
</tr>
<tr>
<td> Eventdetails:<asp:Label ID="label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
    </asp:DataList>--%>
    </div>
...............................................................


......................................................................

and your code behind should contain this:


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Events : System.Web.UI.Page
{


    PagedDataSource pgsource = new PagedDataSource();
    int findex, lindex;
    DataRow dr;

    protected void Page_Load(object sender, EventArgs e)
    {
        //During first time page load this method call
        if (!Page.IsPostBack)
        {
            BindDataList();
            LoadDDL();
        }
    }

    public DataTable getTheData()
    {

        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection con = new SqlConnection(connstr);
        con.Open();


        SqlDataAdapter objSQLAdapter = new SqlDataAdapter("select * from Events", con);

        DataSet DS = new DataSet();

        objSQLAdapter.Fill(DS);

        con.Close();
        if (DS.Tables[0].Rows.Count == 0)
        {

            //lbl_msg.Text = "";

            DataList1.Visible = false;

        }

        else
        {

            Session["cnt"] = DS.Tables[0].Rows.Count;

        }

        return DS.Tables[0];

    }

    private void BindDataList()
    {
        //Create new DataTable dt
        DataTable dt = getTheData();
        pgsource.DataSource = dt.DefaultView;

        //Set PageDataSource paging
        pgsource.AllowPaging = true;

        //Set number of items to be displayed in the DataList using drop down list
        if (ddlIndex.SelectedIndex == -1 || ddlIndex.SelectedIndex == 0)
        {
            pgsource.PageSize = 10;
        }
        else
        {
            pgsource.PageSize = Convert.ToInt32(ddlIndex.SelectedItem.Value);
        }


        //Get Current Page Index
        pgsource.CurrentPageIndex = CurrentPage;

        //Store it Total pages value in View state
        ViewState["totpage"] = pgsource.PageCount;

        //Below line is used to show page number based on selection like "Page 1 of 20"
        lblpage.Text = "Page " + (CurrentPage + 1) + " of " + pgsource.PageCount;

        //Enabled true Link button previous when current page is not equal first page
        //Enabled false Link button previous when current page is first page
        lnkPrevious.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Next when current page is not equal last page
        //Enabled false Link button Next when current page is last page
        lnkNext.Enabled = !pgsource.IsLastPage;

        //Enabled true Link button First when current page is not equal first page
        //Enabled false Link button First when current page is first page
        lnkFirst.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Last when current page is not equal last page
        //Enabled false Link button Last when current page is last page
        lnkLast.Enabled = !pgsource.IsLastPage;

        //Bind resulted PageSource into the DataList
        DataList1.DataSource = pgsource;
        DataList1.DataBind();

        //Create Paging in the second DataList "DataListPaging"
        doPaging();
    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        //Add two column into the DataTable "dt"
        //First Column store page index default it start from "0"
        //Second Column store page index default it start from "1"
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");

        //Assign First Index starts from which number in paging data list
        findex = CurrentPage - 5;

        //Set Last index value if current page less than 5 then last index added "5" values to the Current page else it set "10" for last page number
        if (CurrentPage > 5)
        {
            lindex = CurrentPage + 5;
        }
        else
        {
            lindex = 10;
        }

        //Check last page is greater than total page then reduced it to total no. of page is last index
        if (lindex > Convert.ToInt32(ViewState["totpage"]))
        {
            lindex = Convert.ToInt32(ViewState["totpage"]);
            findex = lindex - 10;
        }

        if (findex < 0)
        {
            findex = 0;
        }

        //Now creating page number based on above first and last page index
        for (int i = findex; i < lindex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

        //Finally bind it page numbers in to the Paging DataList
        DataListPaging.DataSource = dt;
        DataListPaging.DataBind();
    }

    private int CurrentPage
    {
        get
        {   //Check view state is null if null then return current index value as "0" else return specific page viewstate value
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return ((int)ViewState["CurrentPage"]);
            }
        }
        set
        {
            //Set View statevalue when page is changed through Paging DataList
            ViewState["CurrentPage"] = value;
        }
    }

    protected void DataListPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("newpage"))
        {
            //Assign CurrentPage number when user click on the page number in the Paging DataList
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            //Refresh DataList "DlistEmp" Data once user change page
            BindDataList();
        }
    }

    protected void lnkFirst_Click(object sender, EventArgs e)
    {
        //If user click First Link button assign current index as Zero "0" then refresh DataList "DlistEmp" Data.
        CurrentPage = 0;
        BindDataList();
    }

    protected void lnkLast_Click(object sender, EventArgs e)
    {
        //If user click Last Link button assign current index as totalpage then refresh DataList "DlistEmp" Data.
        CurrentPage = (Convert.ToInt32(ViewState["totpage"]) - 1);
        BindDataList();
    }

    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        //If user click Previous Link button assign current index as -1 it reduce existing page index.
        CurrentPage -= 1;
        //refresh DataList "DlistEmp" Data
        BindDataList();
    }

    protected void lnkNext_Click(object sender, EventArgs e)
    {
        //If user click Next Link button assign current index as +1 it add one value to existing page index.
        CurrentPage += 1;

        //refresh DataList "DlistEmp" Data
        BindDataList();
    }

    void LoadDDL()
    {
        //Below code is used to bind values in the drop down list
        for (int i = 1; i <= 10; i++)
        {
            ddlIndex.Items.Add(i.ToString());
        }
        ddlIndex.Items.Insert(0, new ListItem("--Select--", "--Select--"));
    }

    protected void ddlIndex_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Set Default current index Zero default and refresh it page size based on Drop Down List selected
        CurrentPage = 0;
        BindDataList();
    }
    protected void DataListPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        //Enabled False for current selected Page index
        LinkButton lnkPage = (LinkButton)e.Item.FindControl("Pagingbtn");
        if (lnkPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkPage.Enabled = false;
        }
    }

}


.....................................................................



finished...............................!