Wednesday 29 February 2012

Grid View Filter With TextBox

Grid View Filter With TextBox/Grid View Filter With Passing Text  

If you require filtering gridview according to the text passing to it,then here is a solution.
here we are passing a column value via TextBox which will sort the column accordingly.



ASPX. Page

 <style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }
.highlight {text-decoration: none;color:black;background:yellow;}
</style><style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }
.highlight {text-decoration: none;color:black;background:yellow;}
</style>
</head>
<body>
    <form id="form1" runat="server">
   <div class="GridviewDiv">
<p>
Enter UserName :
<asp:TextBox ID="txtSearch" runat="server" />&nbsp;&nbsp;
<asp:ImageButton ID="btnSearch" ImageUrl="~/SearchButton.png" runat="server"
Style="top: 5px; position: relative" onclick="btnSearch_Click" />&nbsp;&nbsp;
<asp:ImageButton ID="btnClear" ImageUrl="~/Clearbutton.png" runat="server" Style="top: 5px;
position: relative" onclick="btnClear_Click" /><br />
<br />
</p>
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" DataSourceID="dsDetails" Width="540px" PageSize="10" CssClass="Gridview" >
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("currencyname").ToString()) %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastname" Text='<%# Eval("Big_Unit") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" Text='<%#Eval("Small_Unit") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="dsDetails" runat="server" ConnectionString="<%$ConnectionStrings:ThreadTestConnectionString %>" SelectCommand="select * from tbl_Currency" FilterExpression="currencyname LIKE '%{0}%'">
<FilterParameters>
<asp:ControlParameter Name="currencyname" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
    </form>



CS Code

  using System.Text.RegularExpressions; //Add Namespace



 //Add This Code Inside You CS File

private string SearchString = "";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public string HighlightText(string InputTxt)
    {
        string Search_Str = txtSearch.Text;
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
        // Highlight keywords by calling the
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
    }

    public string ReplaceKeyWords(Match m)
    {
        return ("<span class=highlight>" + m.Value + "</span>");
    }
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        //  Set the value of the SearchString so it gets
        SearchString = txtSearch.Text;
    }
    protected void btnClear_Click(object sender, ImageClickEventArgs e)
    {
        //  Simple clean up text to return the Gridview to it's default state
        txtSearch.Text = "";
        SearchString = "";
        gvDetails.DataBind();
    }

So Result Of This Code Will give You Something Like This....

1)Your Record



2)After The Code Execute..



Download Sample From Here

Monday 20 February 2012

Sorting Grid View In ASP.Net

Sorting Grid View Data In Just One Click On Header ASP.net


GridView control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well. In below sample we are using GridView sorting functionality and sort the columns by just clicking the header name



ASPX Page:


<asp:GridView ID="GridView1" OnSorting="SortRecords" runat="server"

AllowSorting="True" CellPadding="4" DataKeyNames="AutoId" />


You may notice that on the .aspx page, we have specified OnSorting event (that fires SortRecords server side methods) and AllowSorting=true to the GridView. This will make the header of the GridView columns as link (In this case we have set AutoGenerateColumns=true to the GridView, so our GridView columns are automatically generated ). In case we are using BoundField or TemplateField, we can use SortExpression property to set the field name to sort on).



C# Page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Exam_Cell_Default : System.Web.UI.Page
{   
    string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
                if (!IsPostBack)
                {
                BindData();
                }
    }
    protected void SortRecords(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;
        string direction = string.Empty;    
        if (SortDirection == SortDirection.Ascending)
        {
            SortDirection = SortDirection.Descending;
            direction = " DESC";
        }
        else
        {
            SortDirection = SortDirection.Ascending;
            direction = " ASC";
        }
        DataTable table = this.GetData();
        table.DefaultView.Sort = sortExpression + direction;
        GridView1.DataSource = table;
        GridView1.DataBind();
    }

    private void BindData()
    {
    SqlCommand cmd=new SqlCommand...............
    SqlDataAdapter adp=new ........
    DataSet ds=new Dataset;
    adp.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    Session["ssst"]=ds;
    }
   
    public SortDirection SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["SortDirection"];
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }
    private DataTable GetData()
    {
       DataTable table = new DataTable();
        DataSet ds = new DataSet();
        ds = (DataSet)Session["ssst"];
        table = ds.Tables[0];
        // fire Fill method to fetch the data and fill into DataTable
        return table;
    }
}



Conclusion:

When any column of the GridView is clicked, the SortRecords server side method executes that first saves the sort expression and direction (Ascending or Descending order) in the ViewState based on the previous order selected. We have a SortDirection property that saves the current sort direction in the ViewState and based on that the direction is set as ASC or DESC. As the DataSource of this GridView is DataTable so we have used Sort method of its view and set the sort expression. This will sort the rows of the DataTable. After sorting, the GridView data source has been set and the DataBind method has been called. My page output looks below that is sorted by FirstName column.

Friday 17 February 2012

Crystal Reports : Using a specific Group Sort Order

Changing Sort Order of Groups in Crystal Reports


Problem: Membership Invoices are grouped on Finishes , but we wish the invoices output in CalculateNo order.
By default, Crystal sorts on the grouped field.Then What to do?





 IF you have to make your record group by a field(Which by default happen when you create group)
To Sort In In Different Field order you must think your REPORT like this

Group Header #1

Group Header #2

Details Section

Group Footer #2

Group Footer #1






For this you have to first create a group then create another group which will look like this...

in your FIELD EXPLORER





 and below one in GROUP EXPERT



Means  Group  #2 (eg. finish here) Is Under Group  #1 (eg. cal_id here) So First data will SORT IN ORDER BY Group  #1 then SORT IN GROUP BY Group  #2


Hope It Will Help You

Thursday 16 February 2012

How To Show limited characters in Gridview columns

Show limited characters in Gridview columns /
Show the tool-tip for Gridview rows and cells

Often you'll see,when you have a long text in your gridview it get scattered but not in gmail,where long subject included in your mail. Its because its a up to column length that how much text it can show you in which way.So here is a basic sample which do something like that.


1) A sample of ( Email)  limited characters in gmail.








2) After You've  Done Binding In GridView And The Value Are Showing In Gridview.
 You Will Notice You Have Few Things In Your Grid View Events,  Included Databound & RowDataBound.Just Click On RowDataBound And Follow The Below Code.









3) Just Enter The Code Below Under RowDataBound To Show You The Things I've Mentioned Above.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        int i = 0;
        //e.Row.Cells[2].Visible = false;   //you can use it to  hide coloumn in run time
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                i++;
                string s = cell.Text;
                if (cell.Text.Length > 10 && (i == 4))       //i ==4 means start from 4th cell start with [0,1,2,3,4]
                    cell.Text = cell.Text.Substring(0, 10) + "...."; 
                cell.ToolTip = s;           // full text Exist in tooltip
            }
        }
    }


Above Green Marked Text Are Comment To Make You Understand Whats Going On In The Code.



Download Sample from Here








Here are few more way for you requirement!!!


1.Code Behind Approch(C#)_____________________
1.Put this function on code behind




public static string Limit(object Desc, int length)
{
    StringBuilder strDesc = new StringBuilder();
    strDesc.Insert(0, Desc.ToString());

    if (strDesc.Length > length)
        return strDesc.ToString().Substring(0, length) + "..." ;
    else return strDesc.ToString();
}





2.Replace

Text='<%#Eval("Product_Name") %>'


3.From your Template field with
Text='<%# Limit(Eval("Product_Name"), 35) %>'















2. Html Approch(CSS)________________________
<style type="text/css">
       span{
    display:inline-block;
    width:180px;
    white-space: nowrap;
    overflow:hidden !important;
    text-overflow: ellipsis;
}</style>

<span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen look</span>





Wednesday 15 February 2012

Create Folder In ASP.Net Run Time

 Create Directory In ASP.Net Run Time
Sometime you have to keep your files or client files in particular folder
which would be create on run time



     private void CreateDirectoryIfNotExists(string NewDirectory)
    {
        try
        {
            // Checking the existance of directory
            if (!Directory.Exists(NewDirectory))
            {
                //If No any such directory then creates the new one
                Directory.CreateDirectory(NewDirectory);
                Label1.Text = "Directory Created";
            }
            else
            {
                Label1.Text = "Directory Exist";
            }
        }
        catch (IOException _err)
        {
            Response.Write(_err.Message);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string NewDirectory = Server.MapPath("Vijay Negi");
        //New Directory Name in string variable
        CreateDirectoryIfNotExists(NewDirectory);
        //Calling the function to create new directory
    }

Friday 10 February 2012

Javascript Value To Asp.net Page

Accessing HTML control/Javascript Function Value In Asp.net Page 

Some time situation comes where some Javascript effect/jquery or css make work on html control but not in .net control.
then what to do?Here is the solution to make html control interaction with asp.net control.So that there value can easily access by your asp.net control.



In Normal Cases

Just Make Input Text(html control) runat="server".

<input id="Text1"  runat="server" type="text" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   

Now If You Want To transffer Text1 Value To Label1 Just Do This In Your C# Code(In Any Event)


Label1.Text =  Text1.Value;



But SomeTime We Have Fuctions Where We Have Value In Cloud And We Have To Catch Then On Fly.
------------------------------------------------------------------------------------------------------------------
So Here We Start...


Let say you've a html textbox with name txtbox and it has some value...so first thing is we have to save its value to a variable name it C.So that we are sure that the txtbox value is now in a variable and we can pass it to any one.

Next thing is ASP.NET has a control name hiddenControl ,just drag it in your design Page(Because Its Behave As A Mediator Between Html & .Net Control Easily) And finaly.just put that C value in hiddencontrol1



html Control----->var C----------->HiddenControl----->Now Value Is In Your ASP Page!





In HTML

For An Instance Lets Say You Are Firing An Client Side Event(javascript function) Like Below....

<html>
<script>
function yourown()
{
var C=document.getElementById("txtbox").value;
document.getElementById('<%=HiddenField1.ClientID%>').value=C;
return true;
}
 </script>
</html>




In C#

Now Understand The Below Code Where We Are Storing final Value Under HiddenField1 To A string In C# Page

String S=HiddenField1.Value;
Response.Write(S);//Show On Screen
//OR
Label1.Text=S; //Show On Label






Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...