Search This Blog

Tuesday, January 25, 2011

How to show limited characters in gridview or how to limit displayed text length in gridview

I have created one web application for that we have prepared one feedback form to collect feedback from users regarding our application for that we have taken gridview to bind all the feedbacks into one page for the admin view. Here some of the users have given one line of feedback some of the users have given two lines of feedback remaining people have given feedback with bigger matter at that time if we bind all the feedbacks to one gridview at that time gridview size has increased a lot and in some rows matter is small but columns size is bigger. 


For that reason we tried to maintain consistency for entire gridview to maintain consistency for gridview we need to write functionality in Gridview RowDataBound event


Design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Gridview Columns With Limited Characters</title>
</head>
<body>
<form id="form1" runat="server">
<table   cellpadding="0" cellspacing="0" width="300px" align="center">
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" Width="100%" 
CssClass="feedbacklink" AutoGenerateSelectButton="True"  
onrowdatabound="GridView1_RowDataBound" PageSize="5" >
</asp:GridView>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtmsg" runat="server" TextMode="MultiLine"
CssClass="textarea" Width="300px" ></asp:TextBox></td>
</tr>
</table>
</form>
</body>
</html> 


In code behind write this functionality to bind gridview and write functionality in Gridview_Rowdatabound to limit the characters in gridview columns.



string strConn = "Data Source=System;Initial Catalog=SamplesDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGrid();

}
public void bindGrid()
{
SqlConnection con = new SqlConnection(strConn);
DataSet myDataSet = new DataSet();
SqlCommand cmd = new SqlCommand("Select * from Feedback", con);
SqlDataAdapter myDataAdapter = new SqlDataAdapter(cmd);
myDataAdapter.Fill(myDataSet);
GridView1.DataSource = myDataSet;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i = 0;
e.Row.Cells[3].Visible = false;
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell cell in e.Row.Cells)
{
i++;
string s = cell.Text;
if (cell.Text.Length > 25 && (i == 3))
cell.Text = cell.Text.Substring(0, 25) + "....";
cell.ToolTip = s;
}
}
}

Monday, January 10, 2011

Gridview column width when AutoGenerateColumns=true

There are occasions when one may work with a data source that provides dynamic columns. A stored procedure that aggregates year-to-date totals, with columns representing the months-to-date, is an example. Towards the beginning of the year, there are only a few columns of data; towards the end of the year, there are many. When displaying data like this in a DataGrid or a GridView control, it is convenient to set AutoGenerateColumns=true, letting ASP.NET create the necessary display columns at runtime. Unfortunately, columns generated this way are not available to the developer through the grid’s Columns property, and thus the developer lacks the ability to establish column-based formatting.


In the aspx page add this style



<style type="text/css">
.wordwrap
{
    word-break:break-all;
    word-wrap:break-word;
    overflow:hidden;
    width:150px;
}
.sno
{
    word-break:break-all;
    word-wrap:break-word;
    overflow:hidden;
    width:50px;
}
</style>




And in the code behind use this code in the RowDataBound Event of the Gridview
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.Cells.Count > 0)
        {
            for (int i = 1; i > e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].CssClass = "wordwrap";               
            }
        }
        e.Row.Cells[0].CssClass = "sno";
    } 

Show number in Currency format in C#

When building a string for output to a web page, it’s useful to format any currency value in a human-friendly money format. This is extremely easy in C#.

The system format string works like this: {0:C}
For example, the following code example


decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html); 



Numeric Format Specifiers
Specifier Description Example C#
c Currency; specify the number of decimal places $12,345.00 string.Format("Currency: {0:c}", iNbr)
d Whole numbers; specifies the minimum number of digits - zeroes will be used to pad the result 12345 string.Format("Whole: {0:d}", iNbr)
e Scientific notation; specifies the number of decimal places 1.2345e+004 string.Format("Exponential: {0:e}", iNbr)
f Fixed-point; specifies the number of decimal places 12345.00 string.Format("Fixed: {0:f3}", iNbr)
n Fixed-point with comma separators; specifies the number of decimal places 12,345.00 string.Format("Fixed formatted: {0:n3}", iNbr)
p percentage; specifies the number of decimal places 1,234,500.00% string.Format("Percentage: {0:p2}", iNbr)
x Hexadecimal 3039 string.Format("Hexadecimal: {0:x}", iNbr)

Change text in CELL of gridview to bold based on data

Some times we need to make the gridview cell text into bold based on the data from database. By the time we can use the code like the following to make the cell text as bold and can use it.


protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
   
{
       
if (e.Row.RowType == DataControlRowType.DataRow)
       
{
           
if (e.Row.Cells[0].Text.Contains("sometext"))
           
{
                e
.Row.Cells[0].Font.Bold = true;
           
}
       
}
   
}
 

Friday, January 7, 2011

Sorting GridView control Manually in Asp.net using C#

Asp.net SqlDataSource control ease our lives because if you are using SqlDataSource control to bind a GridView control then no need to sorting gridview or paging gridview control since you will achieve it automatically. But if you are using different datasource like Datatable, DataSet then you need to GridView sorting manually. Here in this article I will show you how you can develop GridView Sorting easily. One thing keep in mind that When you need to sort a GridView then each time you have to bind the GridView with data.

So you have two way to hold data:
1. You can read data from database each time
2. You can store data within viewstate or cache

Here I am using asp.net cache since you knew that viewstate will increase the page response time. Ok lets start. Add a page in your project then add a GridView on it. Now from GridView properties set the AllowSorting=true. Now in your each bind column set the sortexpression like below:




<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" AllowSorting="true" OnSorting="GridView1_Sorting" >

<HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="LightGray" />
<AlternatingRowStyle BackColor="LightGray" />
    <Columns>
        <asp:BoundField DataField="Brand" HeaderText="Brand Name" SortExpression="Brand"/>
        <asp:BoundField DataField="Category" HeaderText="Category Name" SortExpression="Category" />
        <asp:BoundField DataField="Product" HeaderText="Product Name" SortExpression="Product"/>
    Columns>
asp:GridView>

SortExpression must be same as DataField property.

Now in page_load method follow my below sample code:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT B.Name Brand,C.Name Category, " +
                    "P.Name Product FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";

            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["dt"] = dt;
            ViewState["Column_Name"] = "Brand";
            ViewState["Sort_Order"] = "ASC";
        }
    }

    //From here you can change your query according to your base table.
    //Now add the Sorting event of your gridview and write the below code:
    //view sourceprint?

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression == ViewState["Column_Name"].ToString())
        {
            if (ViewState["Sort_Order"].ToString() == "ASC")
                RebindData(e.SortExpression, "DESC");
            else
                RebindData(e.SortExpression, "ASC");
        }
        else
            RebindData(e.SortExpression, "ASC");
    }
    //If you look at the code you found that here I am using a method named RebindData.
    //The code for this method is given below:
    //view sourceprint?
    private void RebindData(string sColimnName, string sSortOrder)
    {
        DataTable dt = (DataTable)Cache["dt"];
        dt.DefaultView.Sort = sColimnName + " " + sSortOrder;

        GridView1.DataSource = dt;
        GridView1.DataBind();
        ViewState["Column_Name"] = sColimnName;
        ViewState["Sort_Order"] = sSortOrder;
    }

Thursday, January 6, 2011

How to Print in ASP.NET 2.0

One of the most common functionality in any ASP.NET application is to print forms and controls. There are a lot of options to print forms using client scripts. In the article, we will see how to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
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;
using System.IO;
using System.Text;
using System.Web.SessionState;
public class PrintHelper
{
    public PrintHelper()
    {
    }
    public static void PrintWebControl(Control ctrl)
    {
        PrintWebControl(ctrl, string.Empty);
    }
    public static void PrintWebControl(Control ctrl, string Script)
    {
        StringWriter stringWrite = new StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
        if (ctrl is WebControl)
        {
        Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
        }
        Page pg = new Page();
        pg.EnableEventValidation = false;
        if (Script != string.Empty)
        {
        pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
        }
        HtmlForm frm = new HtmlForm();
        pg.Controls.Add(frm);
        frm.Attributes.Add("runat", "server");
        frm.Controls.Add(ctrl);
        pg.DesignerInitialize();
        pg.RenderControl(htmlWrite);
        string strHTML = stringWrite.ToString();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write(strHTML);
        HttpContext.Current.Response.Write("");
        HttpContext.Current.Response.End();
    }
}

Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(), "onclick", "");
    }
The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :
PrintHelper.PrintWebControl(Panel1);

Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }

What is new in ASP.NET 3.5

Microsoft released ASP.NET 3.5 on November 19, 2007. Along with it, was released Visual Studio 2008. This evolution from ASP.NET 2.0 to ASP.NET 3.5 is quiet gradual. ASP.NET 3.5 uses the same engine as that of ASP.NET 2.0, with some extra features added on top of it. In this article, we will explore the new features added to ASP.NET 3.5. This article assumes that you have been working on ASP.NET 2.0.
New Features in ASP.NET 3.5
ASP.NET AJAX
In ASP.NET 2.0, ASP.NET AJAX was used as an extension to it. You had to download the extensions and install it. However in ASP.NET 3.5, ASP.NET AJAX is integrated into the .NET Framework, thereby making the process of building cool user interfaces easier and intuitive.
The integration between webparts and the update panel is much smoother. Another noticeable feature is that you can now add ASP.NET AJAX Control Extenders to the toolbox in VS2008. Even though this is an IDE specific feature, however I feel it deserves a mention over here for developers, who had to add extenders using source view earlier. It is also worth noting that Windows Communication Foundation (WCF) now supports JSON along with other standard protocols like  SOAP, RSS and POX.
New Controls
The ListView and DataPager are new controls added along with a new datasource control called the LinqDataSource.
ListView
The ListView control is quiet flexible and contains features of the Gridview, Datagrid, Repeater and similar list controls available in ASP.NET 2.0. It provides the ability to insert, delete, page (using Data Pager), sort and edit data. However one feature of the ListView control that stands apart, is that it gives you a great amount of flexibility over the markup generated. So you have a complete control on how the data is to be displayed. You can now render your data without using the tag. You also get a rich set of templates with the ListView control.
DataPager
DataPager provides paging support to the ListView control. The best advantage is that you need not have to keep it ‘tied’ with the control on which the paging is being done. You can keep it anywhere on the page.
DataPager gives you a consistent way of paging with the controls that support it. Currently only ListView supports it as it implements the IPageableItemContainer. However support is likely to be added to other List controls as well.
LINQ
LINQ (Language Integrated Query) adds native data querying capability to C# and VB.NET along with the compiler and Intellisense support. LINQ is a component of .NET 3.5. LINQ defines operators that allow you to code your query in a consistent manner over databases, objects and XML.  The ASP.NET LinqDataSource control allows you to use LINQ to filter, order and group data before binding to the List controls.

ASP.NET Merge Tool
ASP.NET 3.5 includes a new merge tool (aspnet_merge.exe). This tool lets you combine and manage assemblies created by aspnet_compiler.exe. This tool was available earlier as an add-on.
New Assemblies
The new assemblies that would be of use to ASP.NET 3.5 developers are as follows:
·         System.Core.dll - Includes the implementation for LINQ to Objects
·         System.Data.Linq.dll - Includes the implementation for LINQ to SQL
·         System.Xml.Linq.dll - Includes the implementation for LINQ to XML
·         System.Data.DataSetExtensions.dll - Includes the implementation for LINQ to DataSet
·         System.Web.Extensions.dll: Includes the implementation for ASP.NET AJAX (new enhancements added) and new web controls as explained earlier.
Some Other Important Points
1.    ASP.NET 3.5 provides better support to IIS7. IIS7 and ASP.NET 3.5 modules and handlers support unified configuration.
2.    You can have multiple versions of ASP.NET on the same machine.
3.    For those who are wondering what happened to ASP.NET 3.0, well there isn’t anything called ASP.NET 3.0.
4.    VS 2002 worked with ASP.NET 1.0, VS 2003 worked with ASP.NET 1.1, and VS 2005 worked with ASP.NET 2.0. However VS 2008 supports multi-targeting, i.e it works with ASP.NET 2.0, and ASP.NET 3.5.