GridView


Gridview:

*Suppose we have a text box in the gridview and our requirement is to send the value of the  value of the row     which have checked. We have to send the textbox value which user have  entered in runtime by user, along with one column value. Then we will write the code like  below.

    foreach (GridViewRow row in gdvShowList.Rows)
    {
          CheckBox chk;
          chk = ((CheckBox)row.FindControl("chkSelect"));
          if (chk.Checked)
          {
               txt = ((TextBox)row.FindControl("txtRemark"));
               sb.Append(row.Cells[1].Text + "~" + (txt.Text) + "`");
           }
    }
 In the backend we have to split the string and store the those columns value in the  respective column.

* The RowStyle-CssClass property of the GridView has been set as “rowHover”; when GridView renders on the page, each row of the GridView (GridView is rendered on the page as html table) is rendered with “rowHover” CSS class that only takes effect when we mouse hover on the GridView row.

Steps to follow
Define following CSS style in the .css file or on the .aspx page itself.

ASPX Page:

<style type="text/css">
#GridView1 tr.rowHover:hover
{
background-color: Yellow;
font-family: Arial;
}
</style>
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" RowStyle-CssClass="rowHover" ClientIDMode="Static" />
Note that the important thing here is the ID of the GridView. When GridView rendered on the page it’s id should be GridView1 that is why we have set ClientIDMode=static.

The CSS class name is rowHover with filtration that instruct the browser that this CSS class should be applied only to the element having id as “GridView1” with “tr” element having class=”rowHover” and only when user mouse over it.

In this CSS class we have specified the background color to “Yellow” and font family to “Arial”.

If you are working on a master page then you can do the above in the following ways .

Write the below code in Row_Created event of gridview.

public void ItemDataBoundEventHandler1(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='Silver'");
    e.Row.Attributes.Add("onmouseout","this.style.backgroundColor='#FFFBD6'");
  }
}

or You can write the below code in Row_created event of gridview


if (e.Row.RowType == DataControlRowType.Header)
   e.Row.CssClass = "header";

//Add CSS class on normal row.
if (e.Row.RowType == DataControlRowType.DataRow &&
          e.Row.RowState == DataControlRowState.Normal)
   e.Row.CssClass = "normal";

//Add CSS class on alternate row.
if (e.Row.RowType == DataControlRowType.DataRow &&
          e.Row.RowState == DataControlRowState.Alternate)
   e.Row.CssClass = "alternate";

You have to write the CSS code for header,normal and alternate.


*Change ASP.NET GridView Header Text at Runtime

write the following code in the RowDataBound event to change the HeaderText of the 3rd column. Note that column index starts from zero.

protected void GridVie1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check for a condition
if (1 == 1)
{
GridView1.Columns[2].HeaderText = "Price(10 Units)";
}
}

*Display Page count in ASP.NET GridView
protected void GridView1_RowDataBound(object sender,
                                            GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Text = (GridView1.PageIndex + 1) + " of " + GridView1.PageCount;
    }
}

*Set Width of GridView TextBox in Edit mode
To modify the width of a TextBox (inside the GridView control) when the GridView is in Edit Mode, use any of the two approaches:

Using ControlStyle

<asp:GridView ID="gvCustom" runat="server">
    <Columns>
        <asp:BoundField DataField="EmpID" HeaderText="EmployeeID" >
            <ControlStyle Width="150" />
        </asp:BoundField>
    </Columns>
</asp:GridView>
Use ControlStyle CSS Class (Recommended)

<style type="text/css">
.cssWdth
{
    width: 150px;
}
</style>
and in the GridView

<asp:GridView ID="gvCustom" runat="server">
    <Columns>
        <asp:BoundField DataField="EmpID" HeaderText="EmployeeID"
        ControlStyle-CssClass="cssWdth" />
    </Columns>
</asp:GridView>
**************************************************************
If you want to hide the column at run time then do the following :


protected void gdvAdminReport_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[2].Visible = false;
            e.Row.Cells[3].Visible = false;
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[2].Visible = false;
            e.Row.Cells[3].Visible = false;
        }
    }


The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control.This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.

decimal priceTotal = 0;
int quantityTotal = 0;
void detailsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // add the UnitPrice and QuantityTotal to the running total variables
        priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, _
          "UnitPrice"));
        quantityTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
          "Quantity"));
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Text = "Totals:";
        // for the Footer, display the running totals
        e.Row.Cells[1].Text = priceTotal.ToString("c");
        e.Row.Cells[2].Text = quantityTotal.ToString("d");
     
        e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
        e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
        e.Row.Font.Bold = true;
    }
}

***********************************************************************************
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
        if(e.Row.RowType == DataControlRowType.DataRow)
        {
            Decimal ProductPrice = (decimal)DataBinder.Eval(e.Row.DataItem, "UnitPrice");
            if(ProductPrice<20)
            {
                e.Row.ForeColor = System.Drawing.Color.Crimson;
                e.Row.Font.Italic = true;
                e.Row.BackColor = System.Drawing.Color.LightPink;
            }
        }

***************************************************************************************

if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Display the company name in italics.
      e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";

    }
******************************************************************************************
Merge GridView Header Columns

<asp:GridView ID="gvCustom" runat="server" AutoGenerateColumns="false"
        AllowPaging="true" PageSize="5" OnPageIndexChanging="gvPaging"
        OnRowCreated="gvCustom_RowCreated">

Finally write the following code in the RowCreated event


protected void gvCustom_RowCreated(object sender,
    GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        GridView header = (GridView)sender;
        GridViewRow gvr = new GridViewRow(0, 0,DataControlRowType.Header,DataControlRowState.Insert);
        TableCell tCell = new TableCell();
        tCell.Text = "DevCurry Employee Information";
        tCell.ColumnSpan = 4;
        tCell.HorizontalAlign = HorizontalAlign.Center;
        gvr.Cells.Add(tCell);
        // Add the Merged TableCell to the GridView Header
        Table tbl = gvCustom.Controls[0] as Table;
        if (tbl != null)
        {
            tbl.Rows.AddAt(0, gvr);
        }
    }
}
***********************************************************************************************
Add an Image Command Field to a GridView at runtime

If you were looking out to programmatically add an Image Command Field to a GridView, here’s how to do so:

C#

if (!Page.IsPostBack)
{
    CommandField field = new CommandField();
    field.ButtonType = ButtonType.Image;
    field.SelectImageUrl = "~/Images/MyPic.GIF";
    field.ShowSelectButton = true;
    field.HeaderText = "Select";
    GridView1.Columns.Add(field);
    GridView1.DataBind();
}
***************************************************************************************************
Set the Line Color Between Rows in an ASP.NET GridView


Have you wondered how to set the color between two rows in an ASP.NET GridView. The GridView control does not provide a direct attribute for setting a color to the lines between two rows. But here’s how to do it using CSS:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Change Color of Lines</title>
    <style type="text/css">
        .gridLines td
        {
            border-bottom: 1px solid Gray;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
        GridLines="Horizontal" CssClass="gridLines" DataKeyNames="ID" >
        <Columns>
            ...
        </Columns>
    </asp:GridView>
    </div>
    </form>
</body>
</html>
********************************************************************************************************
Programmatically Load a GridView Row in Edit Mode


A user in asp.net forums asked a question about loading a GridView Row programmatically in EditMode. It’s quite simple actually. You just have to set the EditIndex to the row number that needs to be edited and bind the GridView with the datasource. Here’s an example:

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Employee emp = new Employee();
        listEmp = emp.GetEmployees();
        // Add Row in Edit Mode
        GridView1.EditIndex = 3;
        // Bind GridView to its Source
        this.GridView1.DataSource = listEmp;
        this.GridView1.DataBind();
    }
}
*******************************************************************************************
Display Page count in ASP.NET GridView


Continuing my ASP.NET GridView Tips and Tricks series, this post shows how to display the page count in an ASP.NET GridView control

In one of our previous articles, we saw how to Highlight the current page in an ASP.NET GridView pager. Let us extend the example, to show the page count too.

The first step is to set the ShowFooter property to true and add a RowDataBound event to the GridView, as shown below



Next write the following code in the GridView_RowDataBound event

protected void GridView1_RowDataBound(object sender,
                                            GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Text = (GridView1.PageIndex + 1) + " of " + GridView1.PageCount;
    }
}
**************************************************************************************************
Add a Row Number to the GridView


Here’s a simple way to add a Row Number to the GridView. Just add the following tags to your <columns> section of your GridView

 <Columns>                    
     <asp:TemplateField HeaderText="RowNumber">
         <ItemTemplate>
                 <%# Container.DataItemIndex + 1 %>
         </ItemTemplate>
     </asp:TemplateField>
     ...
</Columns>
******************************************************************************************************
How to read hidden field data in GridView Asp.net C#

         <Columns>
             <asp:CommandField ShowSelectButton="True" />

             <asp:TemplateField HeaderText="Product Name">

             <ItemTemplate>

             <asp:HiddenField runat="server" ID="HiddenField1" Value='<%#Eval("ID")%>'></asp:HiddenField>

             <asp:Label runat="server" ID="Label2" Text ='<%#Eval("Name")%>'></asp:Label>

             </ItemTemplate>

             </asp:TemplateField>

             <asp:BoundField DataField="Description" HeaderText="Description" />

             <asp:BoundField DataField="Color" HeaderText="Color" />

             <asp:BoundField DataField="Size" HeaderText="Size" />

         </Columns>

Now under SelectedIndexChanged event write the below code to read hidden field value within gridview template column:        

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

    {
        string sValue = ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;

        Response.Write("Product Id=" + sValue);
    }
   
****************************************************************************
Merge merging or Split spliting GridView Header Row or columns in Asp.Net 2.0 / 3.5

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;

            GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

            TableCell Cell_Header = new TableCell();

            Cell_Header.Text = "Hierarchy";

            Cell_Header.HorizontalAlign = HorizontalAlign.Center;

            Cell_Header.ColumnSpan = 2;

            HeaderRow.Cells.Add(Cell_Header);



            Cell_Header = new TableCell();

            Cell_Header.Text = "Product Name";

            Cell_Header.HorizontalAlign = HorizontalAlign.Center;

            Cell_Header.ColumnSpan = 1;

            Cell_Header.RowSpan = 2;

            HeaderRow.Cells.Add(Cell_Header);


            Cell_Header = new TableCell();

            Cell_Header.Text = "Quantity";

            Cell_Header.HorizontalAlign = HorizontalAlign.Center;

            Cell_Header.ColumnSpan = 3;

            HeaderRow.Cells.Add(Cell_Header);


            GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

        }

    }
******************************************************************************************
GridView.RowDeleted Event

The RowDeleted event is raised when a row's Delete button is clicked, but after the GridView control deletes the row. This enables you to provide an event-handling method that performs a custom routine, such as checking the results of the delete operation, whenever this event occurs.

The following example demonstrates how to use the RowDeleted event to check the result of the delete operation. A message is displayed to indicate to the user whether the operation succeeded.

void CustomersGridView_RowDeleted(Object sender, GridViewDeletedEventArgs e)
  {

    // Display whether the delete operation succeeded.
    if(e.Exception == null)
    {
      Message.Text = "Row deleted successfully.";
    }
    else
    {
      Message.Text = "An error occurred while attempting to delete the row.";
      e.ExceptionHandled = true;
    }

  }
*********************************************************************************************
GridView.RowUpdated Event

The RowUpdated event is raised when a row's Update button is clicked, but after the GridView control updates the row. This enables you to provide an event-handling method that performs a custom routine, such as checking the results of the update operation, whenever this event occurs.

The following example demonstrates how to use the RowUpdated event to check the result of the update operation. A message is displayed to indicate to the user whether the operation succeeded.

 void CustomersGridView_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
  {

    // Indicate whether the update operation succeeded.
    if(e.Exception == null)
    {
      Message.Text = "Row updated successfully.";
    }
    else
    {
      e.ExceptionHandled = true;
      Message.Text = "An error occurred while attempting to update the row.";
    }
  }

********************************************
If you want that in the updating mode you want to bind the dropdownlist & select the required value then you can do in the following ways .

<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label ID="lblGender" runat="server" Text='<%#Eval("Sex") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="rbGenderEdit" runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>

In the row databound event you have to write the below code

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView dRowView = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
RadioButtonList rblGender = (RadioButtonList)e.Row.FindControl("rbGenderEdit");
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("ddlStatusEdit");
rblGender.SelectedValue = dRowView[2].ToString();
dlStatus.SelectedValue = dRowView[3].ToString();
}
}
}
*****************************************************
If from the databse NULL value is returning but you want to the different text in place of NULL then you can achieve by calling the server side method in the following ways.
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# CheckNull(Eval("Location")) %>'/>
</ItemTemplate> </asp:TemplateField>
In the server side code :

protected string CheckNull(object objGrid)
{
if (object.ReferenceEquals(objGrid, DBNull.Value))
{
return "No Record Found";
}
else
{
return objGrid.ToString();
}
}
***************************************************************
Suppose in your Gridview there is a Linkbutton. You want to redirect to a different page by clicking on that button. You also want to send some value using querystring then do the following.
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="lnkname" runat="server" Text='<%#Eval("Name") %>'
PostBackUrl='<%#"~/Default.aspx?ID="+Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Or You can do the above in the following ways by using Hyperlink.
<asp:HyperLinkField DataNavigateUrlFields="ID,Name,Location" 
DataNavigateUrlFormatString="Default.aspx?id={0}&name={1}&loc={2}"
Text="Transfer values to other page" />
**********************************************************
If you don't want to show the header of the gridview then set the properties of gridview
ShowHeader="false" 
**********************************************************
Suppose you have a requirement that based on id value you want to update the row value but you are n't showing the value in the gridview. In that case use DataKeys property of gridview.
<asp:GridView Width="100%" ID="gdvShow" runat="server" 
AutoGenerateColumns="false" AutoGenerateEditButton="True"
onrowcancelingedit="gdvdetailOfOtherbill_RowCancelingEdit"
onrowediting="gdvdetailOfOtherbill_RowEditing"
onrowupdating="gdvdetailOfOtherbill_RowUpdating"
onrowcreated="gdvdetailOfOtherbill_RowCreated" DataKeyNames="id,rowid">
In the row updating event of grid view write the code
int i1 = Convert.ToInt32(gdvShow.DataKeys[e.RowIndex].Values[0]);
int i2 = Convert.ToInt32(gdvShow.DataKeys[e.RowIndex].Values[1]);
Store the values in two variables and use where ever you want to update the row.
*********************************************************
Suppose you are trying to bind a gridview and in the backend there is no record in the table. You want to show some some message when the table has no record. Then set the property of gridview as following.
EmptyDataText="There is no record."
*********************************************************
Suppose you have a gridview and there is delete option in your gridview. You want to show some confirmation message when user click on delete button then do the following.
<asp.LinkButton ......... OnClientClick="return confirm('Are you sure you want               to delete this record ?');"
*********************************************************
If you want to show the footer information in your gridview then do the following.
1. Set the ShowFooter properties of gridview to true. Set FooterText="Total"
2. With in <columns> write the below line.
      <asp:TemplateField HeaderText="Footer">
       <ItemTemplate>
                 <asp:Label ID="lblAmount" runat="server" Text='<%#Eval("Amount")>'>             
      </asp:Label>
      </ItemTemplate>
      <FooterTemplate> 
            <asp:Label ID="lblTotal" runat="server"></asp:Label>
      </FooterTemplate>
      </asp:TemplateField>
     </Columns>
     <FooterStyle BackColor="#336699" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
     </asp:Gridview>
3. Write the code in the Gridview_rowdatabound of gridview.
   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
      decimal grdTotal = 0;
      if (e.Row.RowType == DataControlRowType.DataRow)
{
decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
grdTotal = grdTotal + rowTotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}



Comments