Showing posts with label gridview. Show all posts
Showing posts with label gridview. Show all posts

Mar 15, 2011

Change the color of data in GridView based on its value

In this article, I will demonstrate a simple way to change the color of the data in a GridView based on its value.
Let's set the stage. The GridView in this example will display three different products, each having the following attributes:
  • Product Name - the name of the product
  • Price - a number representing the product's price
  • In Stock - a Boolean value representing if a product is in stock
The value in the "In Stock" column will be either a green true value if the product is in stock or a red false value if the product is out of stock. The following image illustrates what the result will look like:
GridView
First, create a new ASPX web page and add the GridView server control to it as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
                <asp:BoundField DataField="Price" HeaderText="Price" />
                <asp:BoundField DataField="InStock" HeaderText="In Stock" />
            </Columns>
        </asp:GridView>

    </div>
    </form>
</body>
</html>
No magic here. We declared a GridView server control and set the AutoGenerateColumns to false so
that we may add the columns manually. In addition, we added a BoundField control for each of the
columns.Switch to the code behind page and add the following code to the Page_Load event:


.. 

protected void Page_Load(object sender, EventArgs e)
{    
    // Create a DataTable object to hold the products.    
    System.Data.DataTable products = new System.Data.DataTable();     
    
    // Create the columns to represent the products attributes.    
    products.Columns.Add("ProductName", Type.GetType("System.String"));    
    products.Columns.Add("Price", Type.GetType("System.Double"));    
    products.Columns.Add("InStock", Type.GetType("System.Boolean"));     
    
    // Add the first record.    
    products.Rows.Add();    
    products.Rows[0]["ProductName"] = "Pen";        
    products.Rows[0]["Price"] = ".89";    
    products.Rows[0]["InStock"] = "True";     
    
    // Add the second record.    
    products.Rows.Add();    
    products.Rows[1]["ProductName"] = "Stapler";    
    products.Rows[1]["Price"] = "5.99";    
    products.Rows[1]["InStock"] = "False";     
    
    // Add the third record.    
    products.Rows.Add();    
    products.Rows[2]["ProductName"] = "Glue";    
    products.Rows[2]["Price"] = "2.29";    
    products.Rows[2]["InStock"] = "True";     
    
    // Set the products DataTable as the DataSource for the GridView    
    // and Bind it.    
    GridView1.DataSource = products;    
    GridView1.DataBind();
} 

...
 
in a real life scenario, the GridView will most likely get its data from a Database,
       XML file or some other data source, but in this example we will create a 
simple  DataTable object and populate it with some data to represent the products.
        
The first line of code in the Page_Load event creates a DataTable object called products. The next three lines illustrate how to declare the columns that will represent the product attributes. The next few lines illustrate how to add records to the products DataTable object. Finally, the last two lines assign the products DataTable to the GridView and binds it.
If you were to run the web page as is, the results would look similar to the following image:
GridView
Now the fun begins. To help us distinguish products that are in stock from out of stock, we are going to change the color of all true values to green and all false values to red. To accomplish this trick, add a new method named InStockColor in the code behind page as follows:

... 

public System.Drawing.Color InStockColor(string inStock)
{    
    // Test inStock
    // if True return Green, else return Red.    
    if (bool.Parse(inStock))        
        return System.Drawing.Color.Green;    
    else        
        return System.Drawing.Color.Red;
} 

...
The InStockColor method takes a string argument representing the value of the In Stock column. It then tests the value to determine if it is either true or false. Based on the value it returns a Green color for true and a Red color for false.
Switch to the ASPX web page and modify the GridView as follows to call the InStockColor method:

 ...
        
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:TemplateField>
            <HeaderTemplate>In Stock</HeaderTemplate>
            <ItemTemplate> 
                <asp:Label ID="InStockLabel" 
                    runat="server" 
                    Text='<%# Eval("InStock") %>' 
                    ForeColor='<%# InStockColor(Eval("InStock").ToString()) %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

...
 
The only update that was made to the GridView was to change the InStock column from BoundField to TemplateField. The TemplateField provides us with greater control on how to display the column. We used a Label server control and bound its Text and ForeColor properties using the DataBinder Eval() method. Eval() is used to evaluate data-binding expressions during run time. To set the correct color, we set the label’s ForeColor property to the InStockColor method and passed in the value of InStock. The InStockColor method will determine the value and return the appropriate Color to the property.
If you were to rerun the web page again, the results would look similar to the following image.
GridView, color
That was pretty painless. In this article, I demonstrated a simple approach to add some colors to the values in GridView during run time.
Hope this article was useful to you.

--------vamsi--------------------
 



 


 

Jul 9, 2010

what are grid events ?code for dropdown inside grid and binding dropdown

two ways are their to bind the data in the Grid:-
GridID_ItemDatabound()
{
  textbox txt =new textbox(); 
  dataset ds=new dataset();
  ds=bind data from DataBase;
  txt=(textbox)e.item.findcontrol("ddl");
  txt.datasource=ds;
  txt.databind();
}

like that we can bind data to dropdown list through
ItemCommand also

ItemDatabound will fire when ever we are binding the data to
datagrid it will iterate for each row and each Item 

ItemCommand will fire when ever we click on any control in
the datagrid then it will fire but it will refer to the
current row in a datagrid

May 11, 2010

Client-Side Validation for the CheckBoxes Inside a GridView

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Selecting a Checkbox</title>

    <script type="text/javascript">
        var TargetBaseControl = null;
       
        window.onload = function()
        {
            try
            {
                //get target base control.
                TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
            }
            catch(err)
            {
                TargetBaseControl = null;
            }
        }
       
        function TestCheckBox()
        {             
            if(TargetBaseControl == null) return false;
            //get target child control.
            var TargetChildControl = "chkBxSelect";
           
            //get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");
           
            for(var n = 0; n < Inputs.length; ++n)
                if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0 && Inputs[n].checked)
                    return true;                
           
            alert('Select at least one checkbox!');
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField HeaderText="n" DataField="sno">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkBxSelect" runat="server" />
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="btnPost" runat="server" Text="Post" OnClientClick="javascript:return TestCheckBox();"
            OnClick="btnPost_Click" />
        <hr />
        <asp:Label ID="lblMsg" runat="server" Font-Bold="True" ForeColor="Red" Width="268px"></asp:Label>
    </form>
</body>
</html>



code:

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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {       
        if (!IsPostBack)
        {
            GridView1.DataSource = GetDataSource();
            GridView1.DataBind();
        }
    }

    protected DataTable GetDataSource()
    {
        DataTable dTable = new DataTable();
        DataRow dRow = null;
        Random rnd = new Random();
        dTable.Columns.Add("sno");

        for (int n = 0; n < 10; ++n)
        {
            dRow = dTable.NewRow();

            dRow["sno"] = n + ".";

            dTable.Rows.Add(dRow);
            dTable.AcceptChanges();
        }

        return dTable;
    }
    protected void btnPost_Click(object sender, EventArgs e)
    {
        lblMsg.Text = "Form is posted!";
    }
}



Jan 8, 2010

open new window in GridView using OnRowCreated

In GridView using "OnRowCreated" function we can add onClick function.

here is the sample code

html code


<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Click Me"></asp:Label>
</ItemTemplate>
</asp:TemplateField>


and CodeBehind is


protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = (Label)e.Row.FindControl("Label1");
if (l != null)
{
string script = "window.open('Default.aspx');";
l.Attributes.Add("onclick", script);
}
}
}


run the Application and click "Click Me" it will open new window , indirectly we are adding

Eliminate Duplicate records from the Grid View

Most of the time we need to delete duplicate entries from GridView, in this case we can delete it manually also or using onRowcreate also we can remove that .

Example
suppose Mr.Xyz has has more than 2 Account in Blogspot.com site and we want to show
in GridView Person and RelatedBlogs like this





and in this case we dont want to repeat Person name on each row.
- I have a data source

DataTable dtsource = new DataTable();

//Adding columns to datatable
dtsource.Columns.Add("Person");
dtsource.Columns.Add("Related Blog");

//Adding records to the datatable
dtsource.Rows.Add("kiran", "kirank.blog.com");
dtsource.Rows.Add("kiran", "webdevlopmenthelp");
dtsource.Rows.Add("kiran", "www.kiran.com");
dtsource.Rows.Add("mark", "mark.blog.com");
dtsource.Rows.Add("mark", "asp-net.blogspot.com");


put the below code in codebehind


private void GenerateUniqueData(int cellno)
{
//Logic for unique names

//Step 1:

string initialnamevalue = grdUniqueNames.Rows[0].Cells[cellno].Text;

//Step 2:

for (int i = 1; i < grdUniqueNames.Rows.Count; i++)
{

if (grdUniqueNames.Rows[i].Cells[cellno].Text == initialnamevalue)
grdUniqueNames.Rows[i].Cells[cellno].Text = string.Empty;
else
initialnamevalue = grdUniqueNames.Rows[i].Cells[cellno].Text;
}
}



on GridView define property OnRowCreated="GenerateUniqueData" it will search the record via cell and set the Person name as a empty or person name

Highlight Gridview's Row on mouseHover

in Gridview we have seen most of the time we one we take move hover to any row , size of that row or background color or any animation get happen you can do that using css, or java script also.

here i have do that using java script

function gvHigh(tRow,showAct)
{
if (showAct)
{
tRow.style.backgroundColor = '#ff32ss';
}
else
{
tRow.style.backgroundColor = '#ffffff';
}
}

function urlloca(Url)
{
document.location.href = Url;
}



and Define onrowCreated function like this and put your code behind here


protected void gv1_onRowCreated(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in gv1.Rows)
{
gvRow.Attributes["onmouseover"] = "highlight(this, true);";
gvRow.Attributes["onmouseout"] = "highlight(this, false);";
HttpResponse myHttpResponse = Response;
HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
gvRow.Attributes.AddAttributes(myHtmlTextWriter);
}

}



that's it it will help you.
thank you.

Format DateTime in Gridview.

Gridview is using mostly , now i have come up with some small but very important task on how to display Proper date time on Gridview , Basically we are defining standard date time option (date + time) , but some time we only want to display date in this case you can follow the below format.Format Date on Bound Column in Grid View

Suppose you want DOB in short date format without time , then you can simply use DataFormatString ="{0:d}" for Short Date
like this

<asp:BoundField DataField="DOB" HeaderText="DOB" DataFormatString = "{0:d}" />


if you are using above this setting then also it will not work ,coz by default the html encode is turned ON to prevent the Cross site Scripting attack , so for that you need to add one more property as HtmlEncode ="false".


<asp:BoundField DataField="DOB" HtmlEnclode="False" HeaderText="DOB" DataFormatString = "{0:d}" />

if You want Logn Date you can use - DataFormatString = "{0:D}"
if You want Logn Time you can use - DataFormatString = "{0:T}"

If you are using Template comlumn and you want to make your date string in short format then also you can use this suppose your item templates is

<ItemTemplate >
<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB") % >'> </asp:Label >
</ItemTemplate >


Then also you can use like this way:

<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB","{0:D}") % >'> </asp:Label >


Following table will show some date formating ways in Gridview column.



Format Pattern

Name

Example

d


Short date

11/8/2008

D

Long date

Sunday, August 11, 2008


t

Short time

3:32 PM

T

Long time

3:32:00 PM

f

Full date/time
(short time)

Sunday, August 11, 2008 3:32 PM

F

Full date/time
(long time)

Sunday, August 11, 2008 3:32:00 PM

g

General date/time
(short time)

8/11/2008 3:32 PM

G

General date/time
(long time)

8/11/2008 3:32:00 PM

m or M

Month day

August 11

r or R

RFC 1123


Sun, 11 Aug 2008 8:32:00 GMT

s

Sortable date/time

2008-08-11T15:32:00

u


Universable sortable date/time

2008-08-11 15:32:00z

U

Universable sortable date/time

Sunday, August 11, 2008 11:32:00 PM


y or Y

Year month

August, 2008


thanx you,

Jan 6, 2010

merge the header row for the GridView control


some time we want to merge the Gridview Content as well as the Header also ,it was very easy in html you need to simply add the Colspan attribute and with the help of that you can set is (2, 3 )what ever you want. Here is the way you can do that same thing in C# and here is CODEBEHIND Source protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { GridViewRow gvr = e.Row; if (gvr.RowType == DataControlRowType.Header) { GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal); TableCell cell = new TableCell(); cell.ColumnSpan = 2; cell.HorizontalAlign = HorizontalAlign.Center; cell.Text = "Product"; row.Cells.Add(cell); cell = new TableCell(); cell.ColumnSpan = 2; cell.HorizontalAlign = HorizontalAlign.Center; cell.Text = "Category"; row.Cells.Add(cell); GridView1.Controls[0].Controls.AddAt(0, row); } }

Dec 21, 2009

how to add serial number column in a gridview at runtime?



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="sno">

                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>

                        <asp:Label ID="Label1" runat="server">
</asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="id" />

            </Columns>
        </asp:GridView>
 
 

int i = 0;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            i += 1;
            Label lblsno = (Label)e.Row.FindControl("Label1");
            lblsno.Text = i.ToString();
            
        }

    }

 
 
 
 
 


Gridview gridlines not showing in ie

 gvjobcards.Attributes.Add("bordercolor", "black");
add this staement in  page load u will get gridlines in internet explorer

Oct 21, 2009

How to refresh an ASP.NET GridView automatically at regular intervals


Then in the code behind, add the following code which refreshes the GridView after every minute

C#

protected void Timer1_Tick(object sender, EventArgs e)

{

GridView2.DataBind();

}