Saturday 22 September 2012

Autocomplete using j query in asp.net code



Just put  below lines in head section of page :


 <script type="text/javascript">
                $(function () {
                    initializer();
                });
                var prmInstance = Sys.WebForms.PageRequestManager.getInstance();

                prmInstance.add_endRequest(function () {
                    //you need to re-bind your jquery events here
                    initializer();
                });
                function initializer() {
                    $("#<%=txtPartyNameSearch.ClientID%>").autocomplete('autoCmp.ashx')
            .result(function (event, data, formatted) {
                if (data) {
                    $("#<%= hidrefguagecode.ClientID %>").val(data[1]);
                }
                else {
                    $("#<%= hidrefguagecode.ClientID %>").val('-1');
                }
            });
                } 
</script>


Code for text box:




 <asp:TextBox ID="txtPartyNameSearch" runat="server" CssClass="TextBoxNew">
                                            </asp:TextBox>
                                            <asp:HiddenField ID="hidrefguagecode" runat="server" />


And add ashx file in your solution 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
namespace CS.WEB.UI
{
    /// <summary>
    /// Summary description for AutoCmp
    /// </summary>
    public class AutoCmp : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string prefixText = context.Request.QueryString["q"];
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager
                        .ConnectionStrings["ConnectionStr"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select PartyName from tblCustomerDetail where PartyName  LIKE '" + prefixText + "%'";

                    cmd.Parameters.AddWithValue("@SearchText", prefixText);
                    cmd.Connection = conn;
                    StringBuilder sb = new StringBuilder();
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            sb.Append(sdr["PartyName"])
                                .Append(Environment.NewLine);
                        }
                    }
                    conn.Close();
                    context.Response.Write(sb.ToString());
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


Tuesday 18 September 2012

how to set auto serial number in asp.net gridview


Design view:







aspx code:

<asp:TemplateField HeaderText="S.No">
                       <ItemTemplate>
                       <%#Container.DataItemIndex+1 %>
                       </ItemTemplate>
 </asp:TemplateField>

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

Thursday 13 September 2012

How to Create Aspnetdb, Asp.net membership provider database using aspnet_regsql command - asp.net membership provider,role provider,profile provider



ASP.NET Membership

ASP.NET membership is a built in way to validate and store user credentials.And Asp.Net membership helps in user authentication in websites. We can implememt membershipprovider by Asp.net Forms authentication and Login control.

Purppose Of Membeship provider

1. Create new user with username and password.

2. Storing membership information in Sql Server,Active directory etc.

3.Authentication of users. By using ASP.NET login control,ASp.NET usercreation wizard etc implement complete authentication system.

4.Fascilitate role management etc

The database used to access membership database is normaly created with name ASPNETDB.MDF. Here is how to install ASPNETDB database


Creating ASPNETDB DATABASE in your SQLEXPRESS
ASPNETDB.MDF is membership provider database and is used for storing and retrieving
membership data from database and here we are going to see how to create membership provider database . The command used to create Aspnetdb.mdf is ASPNET_RegSQL.EXE


1.Start->Programs->Microsoft visual studio 2005->visual studio tools->Visual Studio 2005 command prompt. Type ASPNET_RegSQL.EXE in the visual Studio 2005 command prompt

2. A wizard with the heading " Welcome To The Asp.Net Sql Server Wizard " will be displayed. Here need to click Next

3. Next a wizard with " Select Setup Option " will displayed. Now we need to select setup option “Configure sql server for application purpose is default”. Select which one you wants and next.

4. A window with " Select Sql Server Database " Will be shown Now we need to select our sql server database. Here needs to set server, authentication type and database.
If select the default name"aspnetDb.mdf" will be selected. If you wants to modify existing database select that database.

5.Now A confirm will be displayed with heading "Confirm your Settings". Now check servername and database name and click next.

code to get one table schema into other table


            DataTable _dataTable = PrintData(1);
            // Copy from the results of a Select method.
            DataTable _DataTable2 = _dataTable.Clone();

            foreach (GridViewRow item in GVPendingDemand.Rows)
            {
                string lotId = GVPendingDemand.Rows[item.RowIndex].Cells[1].Text;
                CheckBox chk = item.FindControl("Chk") as CheckBox;
                if (chk.Checked)
                {
                    DataRow[] dr = _dataTable.Select("LotDemandId='" + lotId + "'");
                    if (dr.Length > 0)
                    {
                        for (int i = 0; i < dr.Length; i++)
                        {
                            _DataTable2.ImportRow(dr[i]);
                        }

                    }
                }
             
            }

Tuesday 11 September 2012

SQL DATEDIFF Function


SQL DATEDIFF Function

Returns the number of date and time boundaries crossed between two dates

SQL DATEDIFF Syntax
DATEDIFF ( DatePart , StartDate , EndDate )

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate ='2007-06-05'
SET @EndDate ='2007-08-05'

SELECT DATEDIFF(Year, @StartDate, @EndDate) AS NewDate

Return Value = 0 Year


SELECT DATEDIFF(quarter, @StartDate, @EndDate) AS NewDate
Return Value = 1 quarter

SELECT DATEDIFF(Month, @StartDate, @EndDate) AS NewDate
Return Value = 2 Month


SELECT DATEDIFF(dayofyear,@StartDate, @EndDate) AS NewDate
Return Value = 61 day


SELECT DATEDIFF(Day, @StartDate, @EndDate) AS NewDateReturn Value = 61 Day


SELECT DATEDIFF(Week, @StartDate, @EndDate) AS NewDate
Return Value = 9 Week


SELECT DATEDIFF(Hour, @StartDate, @EndDate) AS NewDateReturn Value = 1464 Hour


SELECT DATEDIFF(minute, @StartDate, @EndDate) AS NewDate
Return Value = 87840 minute


SELECT DATEDIFF(second, @StartDate, @EndDate) AS NewDateReturn Value = 5270400 second


DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate ='2007-06-05'
SET @EndDate ='2007-06-06'

SELECT DATEDIFF(millisecond, @StartDate, @EndDate) AS NewDate

Return Value = 86400000 millisecond

Sunday 2 September 2012

How to Group Gird Row Wise








 protected void GvGatePassSummary_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           

            if (e.Row.RowType == DataControlRowType.DataRow)
            {   //We're only interested in Rows that contain data
                //get a reference to the data used to databound the row


                DataRowView drv = ((DataRowView)e.Row.DataItem);
                if (previousCat == drv["GatePassNo"].ToString() && GatePassDate == drv["GatePassDate"].ToString())
                {
                    //If it's the same category as the previous one
                    //Increment the rowspan
                    if (GvGatePassSummary.Rows[firstRow].Cells[0].RowSpan == 0)
                        GvGatePassSummary.Rows[firstRow].Cells[0].RowSpan = 2;
                    else
                        GvGatePassSummary.Rows[firstRow].Cells[0].RowSpan += 1;
                    e.Row.Cells.RemoveAt(0);


                    if (GvGatePassSummary.Rows[firstRow].Cells[1].RowSpan == 0)
                        GvGatePassSummary.Rows[firstRow].Cells[1].RowSpan = 2;
                    else
                        GvGatePassSummary.Rows[firstRow].Cells[1].RowSpan += 1;
                    //Remove the cell                
                    e.Row.Cells.RemoveAt(0);

                    if (GvGatePassSummary.Rows[firstRow].Cells[2].RowSpan == 0)
                        GvGatePassSummary.Rows[firstRow].Cells[2].RowSpan = 2;
                    else
                        GvGatePassSummary.Rows[firstRow].Cells[2].RowSpan += 1;
                    //Remove the cell                
                    e.Row.Cells.RemoveAt(1);
                }
                //if (GatePassDate == drv["GatePassDate"].ToString())
                //{
                //    if (GvGatePassSummary.Rows[firstRow].Cells[1].RowSpan == 0)
                //        GvGatePassSummary.Rows[firstRow].Cells[1].RowSpan = 2;
                //    else
                //        GvGatePassSummary.Rows[firstRow].Cells[1].RowSpan += 1;
                //    //Remove the cell                
                //    e.Row.Cells.RemoveAt(0);
                //}
                // GatePassDate == drv["GatePassDate"].ToString()
                else //It's a new category
                {                //Set the vertical alignment to top
                    e.Row.VerticalAlign = VerticalAlign.Middle;
                    //Maintain the category in memory
                    previousCat = drv["GatePassNo"].ToString();
                    GatePassDate = drv["GatePassDate"].ToString();
                    CustName = drv["PartyName"].ToString();
                    firstRow = e.Row.RowIndex;
                }
            }
     
        }

radio button in gridview

.cs code:

 your going to use a grid view and u want to put a radio button on a TemplateField to act as a pointer to your selection just use this code on the rbSelector_CheckedChanged()..






protected void rbSelector_CheckedChanged(object sender, System.EventArgs e)
        {

            //Clear the existing selected row
            foreach (GridViewRow oldrow in GVLotList.Rows)
            {
                ((RadioButton)oldrow.FindControl("rbSelector")).Checked = false;
            }

            //Set the new selected row
            RadioButton rb = (RadioButton)sender;
            GridViewRow row = (GridViewRow)rb.NamingContainer;
            ((RadioButton)row.FindControl("rbSelector")).Checked = true;
        }


aspx page code:


 <asp:TemplateField HeaderStyle-Width="30px">
       <ItemTemplate>
        <asp:RadioButton ID="rbSelector" AutoPostBack="true" runat="server"                  OnCheckedChanged="rbSelector_CheckedChanged" />
        </ItemTemplate>
   </asp:TemplateField>

Wednesday 29 August 2012

gridview cell merge options


In this article write the code to merge column & cells in same data in cells. I am described how to merge cells in Gridview in ASP.NET . In this article I am add OnRowDataBound Event of gridview and use RowSpan of cells.

In this article I am connecting with sql database & in a table I have some columns like college description, college name with branch wise.. both of colleges have many branches so I merge college name Like this


on Aspx page

In aspx page write Gridview Control then add SqldataSource . Configure database with collge table and fill grid view. All data show in gridview. Add event in gridview  OnRowDataBound="GridView1_RowDataBound"

 

In aspx.cs page write this code

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {   //We're only interested in Rows that contain data
            //get a reference to the data used to databound the row
            DataRowView drv = ((DataRowView)e.Row.DataItem);
            if (previousCat == drv["Collegename"].ToString())
            {
                //If it's the same category as the previous one
                //Increment the rowspan
                if (GridView1.Rows[firstRow].Cells[0].RowSpan == 0)

                    GridView1.Rows[firstRow].Cells[0].RowSpan = 2;
                else
                    GridView1.Rows[firstRow].Cells[0].RowSpan += 1;
                //Remove the cell
                e.Row.Cells.RemoveAt(0);
            }
            else //It's a new category
            {                //Set the vertical alignment to top
                e.Row.VerticalAlign = VerticalAlign.Top;
                //Maintain the category in memory
                previousCat = drv["Collegename "].ToString();
                firstRow = e.Row.RowIndex;
            }
        }
    }
Then you run your page & Look like Merger data in a Gridview

Grid view operation tips


in this article i want to share Some Cool and useable Tips and Tricks For GridView

1. Pop-up a Confirmation box before Deleting a row in GridView

Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:

<asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="btnDel" runat="server" Text="Delete"
            CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />
      </ItemTemplate>
</asp:TemplateField>


2. Paging and Sorting in GridView without using Datasource control

<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" 
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton) {    string newSortDirection = String.Empty;
   switch (sortDirection)    {       case SortDirection.Ascending:          newSortDirection = "ASC";          break;
      case SortDirection.Descending:          newSortDirection = "DESC";          break;    }
   return newSortDirection }
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e) {    gridView.PageIndex = e.NewPageIndex;    gridView.DataBind(); }
protected void gridView_Sorting(object sender, GridViewSortEventArgs e) {    DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)    {       DataView dataView = new DataView(dataTable);       dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;       gridView.DataBind();    } }


3. Enable Disable Controls inside a GridView

Disable controls on some rows, when a certain condition is satisfied. In this snippet, we will see how to disable editing for rows that have the CategoryName as ‘Ready’. Use the following code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                Label lblControl = (Label)e.Row.Cells[2].FindControl("lblCategoryName");

                if(lblControl.Text == "Ready")
                {
                    e.Row.Cells[0].Enabled = false;
                }
            }
        }
    }


4. How to Add a Row Number to the Gridview

add the following tags to <columns> section of your GridView
<asp:TemplateField>
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>
</asp:TemplateField>

5. How to programmatically hide a column in the GridView
GridView1.HeaderRow.Cells[2].Visible = false;
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            gvr.Cells[2].Visible = false;
        }

6. Displaying Empty Data in a GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" EmptyDataText="No data available"
            ShowFooter="true" AllowPaging="True" AllowSorting="True"
            PageSize="5" OnRowDataBound="GridView1_RowDataBound">

7. Change the color of a GridView Row based on some condition
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;
            string catName = Convert.ToString(drv["CategoryName"]);
            if (catName.Trim() == "Confections")
                e.Row.BackColor = System.Drawing.Color.LightBlue;
        }
    }


8. Highlight an ASP.NET GridView row on Mouse Hover

<head id="Head1" runat="server">
    <title>Highlight Row on Hover</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("tr").filter(function() {
                return $('td', this).length && !$('table', this).length
            }).css({ background: "ffffff" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#ffffff" }); }
                );
        });
    </script>
   
</head>


Output:


9. How to programmatically enable/disable a control in the GridView when in the Edit Mode

If you want to quickly take a decision whether to enable or disable a control when the user edits the row, then use the Enabled attribute and set it to a method that returns a bool value:
<asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCategoryName" runat="server" Enabled='<%# EnableDisableTextBox() %>' Text='<%# Bind("CategoryName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
C#
    protected bool EnableDisableTextBox()
    {
        if (1 == 1)
            return false;
    }

Tuesday 19 June 2012

How to allow sorting with gridview header column in asp.net

Here is complete code for allow sorting in asp.net gridview:

 public SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {  ViewState["dirState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["dirState"];
        }
        set
        {        ViewState["dirState"] = value;
        }

    }
        protected void gvShowRecord_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortingDirection = string.Empty;

            if (dir == SortDirection.Ascending)
            {
                dir = SortDirection.Descending;

                sortingDirection = "Desc";
            }

            else
            {
                dir = SortDirection.Ascending;
                sortingDirection = "Asc";
            }

            DataView sortedView = new DataView(BindGridOfParticipantDetail());

            sortedView.Sort = e.SortExpression + " " + sortingDirection;

            gvShowRecord.DataSource = sortedView;

            gvShowRecord.DataBind();
        }
    }


and design page require some settings  as


1. AllowSorting="True"   onsorting="gvShowRecord_Sorting"

 2. <asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />


Thursday 14 June 2012

how to create zip folder and download in asp.net


  
using ionic.zip;
 public string  SaveStreamToFile()
        {
            
             CV.Programs.Entity.ParticipantDocument participantDocument = new CV.Programs.Entity.ParticipantDocument();
            participantDocument.ParticipantId = Convert.ToInt32(Session["ParticipantId"]);
            ParticipantDocumentBLL participantDocumentBLL = new ParticipantDocumentBLL();
            DataTable _dataTable=participantDocumentBLL.GetParticipantDocument(participantDocument);
            string directoryPath = Server.MapPath("~/abc/ParticipantDOC/") +"admin"+ Session["ParticipantId"].ToString() + "" + DateTime.Now.ToString("ss");
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
                ViewState["DirName"] = directoryPath;
            }
            for (int i = 0; i < _dataTable.Rows.Count; i++)
            {
                if (Convert.ToString(_dataTable.Rows[i]["UploadedDocumentName"]) != "")
                {
                    byte[] file = null;
                    file = _dataTable.Rows[i]["UploadedDocument"] as byte[];
                    string filename = _dataTable.Rows[i]["UploadedDocumentName"].ToString();
                    string strExtenstion = Path.GetExtension(filename);
                    // Create a FileStream object to write a stream to a file
                    using (FileStream fileStream = System.IO.File.Create(directoryPath+"/" + Session["ParticipantId"] + "_"+i+"Document" + strExtenstion))
                    {
                        fileStream.Write(file, 0, file.Length);
                    }
                }
            }
            return directoryPath;
        }




        protected void DownloadAllDocuments(string dirPath)
        {


            using (MemoryStream ms = new MemoryStream())
            {
                // create new ZIP archive within prepared MemoryStream
                //Directory.CreateDirectory(Server.MapPath("/KIZUNA/ParticipantPDF/" + Session["UserLoginId"].ToString() + "_" + Session["ParticipantId"] + ".zip"));
                //ZipFile zip =ZipFile.Create(Server.MapPath("/ abc /ParticipantPDF/"+Session["UserLoginId"].ToString()+"_"+Session["ParticipantId"]+".zip"));                
                    // add some files to ZIP archive
               
                    Response.Clear();
                    Response.AddHeader("content-disposition", "filename=sample.zip");
                    Response.ContentType = MimeType(".zip");
                    //string[] allFiles = Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories);
                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddDirectory(dirPath);
                        zip.Save(Response.OutputStream);
                    }


                    //zip.BeginUpdate();
                    //for (int i = 0; i < allFiles.Length; i++)
                    //{
                    //    zip.Add(allFiles[i].ToString());
                       
                    //}
                    //ms.WriteTo(Response.OutputStream);
                    //// clear response stream and set the response header and content type
                   
                    


                    //// write content of the MemoryStream (created ZIP archive) to the response stream
                   
                    //zip.CommitUpdate();
                    //zip.Close();
                
            }
            if (Directory.Exists(dirPath))
            {
                Directory.Delete(dirPath, true);
                //Directory.CreateDirectory(directoryPath);
                //ViewState["DirName"] = directoryPath;
            }
            if (Directory.Exists(Server.MapPath("/ abc /ParticipantPDF/" + Session["UserLoginId"].ToString() + "_" + Session["ParticipantId"] + ".zip")))
            {
                Directory.Delete(Server.MapPath("/ abc /ParticipantPDF/" + Session["UserLoginId"].ToString() + "_" + Session["ParticipantId"] + ".zip"), true);
                //Directory.CreateDirectory(directoryPath);
                //ViewState["DirName"] = directoryPath;
            }
            // close the current HTTP response and stop executing this page
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            
           


        }
Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft