Search This Blog

Wednesday, March 30, 2011

Gridview column multiplication using javascript and item template textbox.


Gridview is more powerful data control in the ASP.NET Data controls list, when we need to use a gridview with some column multiplication process that time we need to use javascript to achieve the multiplication.

Consider there is three columns in the gridview with textboxes in the item templates, by the time we need to enter the value in the first column textbox and while entering the text in the second column textbox we need the multiplied result in the third column textbox.

We need to do the calculation on the fly in the client side without using any server side function, the javascript is more useful when we need to do some client side processes. Here we going to see some client side multiplication using javascript and a little bit code in the code behind.

GridView Martkups:

<asp:GridView ID="gvSample" runat="server" AllowSorting="True"
AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowDataBound="gvSample_RowDataBound" AutoGenerateColumns="False"
ShowFooter="True">
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtTest1" runat="server" Width="100px"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtTotal2" runat="server" Width="100px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtTest2" runat="server"  Width="100px"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtTotal1" runat="server" Width="100px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtTest3" runat="server" Width="100px"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootTotal" runat="server" Width="100px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

JavaScrript:
<script type="text/javascript">
function GetClientId(strid)
{
var count=document.forms[0].length;
var i = 0 ;
var eleName;
for (i = 0 ; i < count ; i++ )
{
eleName = document.forms[0].elements[i].id;
pos=eleName.indexOf(strid) ;
if(pos >= 0) break;
}
return eleName;
}
function GetTotal(tQuantity_id, tPrice_id, lTotal_id) {
var obj_tQuantity = document.getElementById(tQuantity_id);
var obj_tPrice = document.getElementById(tPrice_id);
var obj_lTotal = document.getElementById(lTotal_id);
if (obj_tQuantity.value != "" && obj_tPrice.value != "") {
obj_lTotal.value = parseInt(obj_tQuantity.value) * parseInt(obj_tPrice.value);
}

var txtTotal = 0;
var passed = false;
var id = 0;
totalDTH = 0;
totalMCF = 0;
// Get the gridview
var grid = document.getElementById("<%= gvSample.ClientID%>");

// Get all the input controls (can be any DOM element you would like)
var inputs = grid.getElementsByTagName("input");

// Loop through all the DOM elements we grabbed
for (var i = 0; i < inputs.length; i++) {

if (inputs[i].name.indexOf("txtTest3") > 1) {
if (inputs[i].value != "") {
totalDTH = totalDTH + parseInt(inputs[i].value);
}
}
}
document.getElementById(GetClientId("txtFootTotal")).value = totalDTH;
document.getElementById(GetClientId("txtTotal1")).value = 20;
document.getElementById(GetClientId("txtTotal2")).value = 20 + totalDTH;
return false;
}
</script>

C# Code behind:

we need to add the javascript for the textboxes in the gridview's item template. So we using the row databound event to add the javascript to the textboxes. In the onchange event of the textbox we doing the calculations. And finally we showing the calculated data in the footer with the running total and a tax calculation also.

protected void gvSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtTempPrice = e.Row.FindControl("txtTest1") as TextBox;
TextBox txtTempQuantity = e.Row.FindControl("txtTest2") as TextBox;
TextBox txtTempResult = e.Row.FindControl("txtTest3") as TextBox;
txtTempPrice.Attributes.Add("onchange", "javascript:return GetTotal('" + txtTempPrice.ClientID + "', '" + txtTempQuantity.ClientID + "', '" + txtTempResult.ClientID + "');");
txtTempQuantity.Attributes.Add("onchange", "javascript:return GetTotal('" + txtTempPrice.ClientID + "', '" + txtTempQuantity.ClientID + "', '" + txtTempResult.ClientID + "');");
}
}

DropDownList in Gridview EditItemTemplate value Selected


In the gridview we can use textbox by default for the edit template, that is to edit a row we can have textbox. Some times we may need of a dropdownlist in the edit template of the gridview, By the time we have to use the edit template with a dropdownlist and we need to highlight the selected item in the dropdownlist for the edit item. For such scenario refer the following code lines for a better understanding.

GridView markups for the edit template:

</asp:TemplateField>
<asp:TemplateField HeaderText="Item Details">
<ItemTemplate><%# Eval("Item") %></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlItems" DataSource='<%# GetAllItems() %>' DataTextField="Item"
DataValueField="ItemID" SelectedValue='<%# Bind("ItemID") %>' runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>

In the code behind:

The method to get all the items details from the database must be a public method, that means the access modifier of the GetAllItems() method should be public. And its return type must a dataset or a datatable.


public DataSet GetAllItems()
{
try
{
DataSet dsItems = new DataSet();

//Your method to fill the dataset from the DataBase

ViewState["ItemTable"] = dsItems;
return dsItems;
}
catch (Exception ex)
{
throw ex;
}

Thursday, March 24, 2011

Highlight the gridview last updated row


Hi most of the time we need to highlight the gridview last update row, because after updating we rebinding the data to the gridview. So it will show the first page only. By the time we need to high light the gridview row, with its page index also.

But we need datakeynames for the gridview, here I used the customer id as the datakeyname. The data key name also must be a numeric field then only its easily to handle.

The css style format for the updated row is as follows
<style type="text/css">
.UpdateRecordCss td
{
border-bottom:solid 1px green;
border-top:solid 1px green;
font-weight:bold;
}
</style>

add the above css in your aspx code and do the following things in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
BindGrid();
if(HttpContext.Current.Request["myGVPageId"] != null)
{
gvSample.PageIndex = Convert.ToInt32(HttpContext.Current.Request["myGVPageId"]);
}
}
}

protected void gvSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int id = Convert.ToInt32(gvSample.DataKeys[e.Row.RowIndex].Value.ToString());
if (id == Convert.ToInt32(Session["pkid"]))
e.Row.CssClass = "UpdateRecordCss";
}
}

protected void gvSample_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtCustCode = (TextBox)gvSample.Rows[e.RowIndex].FindControl("txtECustCode");
Session["pkid"] = txtCustCode.Text.ToString();
}

protected void gvSample_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSample.EditIndex = -1;
TextBox txtCustCode = (TextBox)gvSample.Rows[e.RowIndex].FindControl("txtECustCode");
gvSample.PageIndex = Convert.ToInt32(Session["pgindex"]);
Session["pkid"] = txtCustCode.Text.ToString();
BindGrid();
}

Tuesday, March 15, 2011

Change gridview Column Order When AutoGeneratedColumns is true

Here we going to discuss about the gridview columns reorder process when the Auto Generated Columns is true. By the time we need to specify a particular gridview cell and have to remove it  and then have to add it in the same gridview. This all have to be done with the Gridview rowdatabound event like the following code snippets.

C# Code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
List<TableCell> cells = new List<TableCell>();
foreach (DataControlField column in GridView1.Columns)
{
//Getting first Column of the Gridview
TableCell cell = row.Cells[0];

//Remove that cell from the gridview
row.Cells.Remove(cell);

//Adding that cell as the last cell in the gridview
cells.Add(cell);
}
// Add cells
row.Cells.AddRange(cells.ToArray());
}



VB.NET Code:

Imports System.Collections
Imports System.Collections.Generic

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim row As GridViewRow = e.Row
Dim cells As New List(Of TableCell)()
For Each column As DataControlField In GridView1.Columns
'Getting first Column of the Gridview
Dim cell As TableCell = row.Cells(0)

'Remove that cell from the gridview
row.Cells.Remove(cell)

'Adding that cell as the last cell in the gridview
cells.Add(cell)
Next
' Add cells
row.Cells.AddRange(cells.ToArray())
End Sub

End Class

Monday, March 14, 2011

Highlight gridview row when row is selected using javascript


Many of us like to highlight or supposed to highlight the selected row in the grid view control, if we are doing it in the server side it will take time when there is no of rows, if we go for java script then it will be easy and we can do it with a few lines of server side coding.

In this example I have used the alternate row color from my grid view color, so If you need the same way you have to change the alternate row color in this java script.

Javascript:

<script type="text/javascript">
var gridViewCtlId = '<%=gvSample.ClientID%>';
var gridViewCtl = null;
var curSelRow = null;
var oddrowcolor = null;
var evenrowcolor = null;
function getGridViewControl() {
if (null == gridViewCtl) {
gridViewCtl = document.getElementById(gridViewCtlId);
}
}
function onGridViewRowClick(rowIndex) {
var table = document.getElementById("gvSample");
for (var i = 1; i < table.rows.length-1; i++) {
if (i % 2 != 1) {
table.rows[i].style.backgroundColor = '#FFFFFF';
}
else {
table.rows[i].style.backgroundColor = '#fffbd6';
}
}
var selRow = getClickedRow(rowIndex);
if (null != selRow) {
selRow.style.backgroundColor = '#FFCC33';
}
}

function getClickedRow(rowIndex) {
getGridViewControl();
if (null != gridViewCtl) {
return gridViewCtl.rows[rowIndex];
}
return null;
}
</script>

C# Code Behind:

protected void gvSample_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int rowid = Convert.ToInt32(e.Row.RowIndex) + 1;
e.Row.Attributes.Add("onclick", "onGridViewRowClick('" + rowid.ToString() + "')");
}
}

Thursday, March 10, 2011

Bind the Excel Data to a GridView using an OleDbDataAdapter

I have seen a lot of users asking how to import data from an excel sheet into an ASP.NET GridView.
Here in this article we will see how to import a excel sheet to the gridview, First we will browse the file and we will copy that file to the web directory from there we will bind the first excel sheet into the gridview.


Here we can load Excel 1997, 2003 and 2007.


ASPX Page: 



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
Font-Names="Verdana" Font-Size="Small" ForeColor="#333333">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<table>
<tr>
<td><asp:FileUpload ID="fupExcel" runat="server" Font-Names="Verdana"
Font-Size="Small" /></td>
</tr>
<tr>
<td><asp:Button ID="btnUpload" runat="server" Text="Upload" Font-Names="Verdana"
Font-Size="Small" onclick="btnUpload_Click" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>

Code Behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.IO;
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.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection uploads = HttpContext.Current.Request.Files;
for (int i = 0; i < uploads.Count; i++)
{
HttpPostedFile upload = uploads[i];
if (upload.ContentLength == 0)
continue;
string c = System.IO.Path.GetFileName(upload.FileName);
try
{
upload.SaveAs(Server.MapPath("Invoices\\") + c);
}
catch (Exception Exp)
{
throw (Exp);
}
}
if (fupExcel.PostedFile != null)
{
HttpPostedFile attFile = fupExcel.PostedFile;
int attachFileLength = attFile.ContentLength;
if (attachFileLength > 0)
{
if (fupExcel.PostedFile.ContentLength > 0)
{
string Extension = Path.GetExtension(fupExcel.PostedFile.FileName);
string inFileName = Path.GetFileName(fupExcel.PostedFile.FileName);
string pathDataSource = Server.MapPath("Invoices\\") + inFileName;

string conStr = "";
if (Extension == ".xls" || Extension == ".xlsx")
{
switch (Extension)
{
case ".xls": //Excel 1997-2003
conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + pathDataSource.ToString() + "';" + "Extended Properties=Excel 8.0;";
break;
case ".xlsx": //Excel 2007
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='" + fupExcel.PostedFile.FileName.ToString() + "';" + "Extended Properties=Excel 8.0;";
break;
default:
break;
}

OleDbConnection connExcel = new OleDbConnection(conStr.ToString());
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
connExcel.Open();
DataSet ds = new DataSet();
//Selecting Values from the first sheet
//Sheet name must be as Sheet1
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conStr.ToString());
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
if (GridView1.Columns.Count > 0)
{
}
connExcel.Close();
if (File.Exists(pathDataSource))
{
File.Delete(pathDataSource);
}
}
else
{
//Show your error in any error controls
}
}
else
{
fupExcel.Focus();
GridView1.DataSource = null;
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}

Screen Samples:

Initial screen will be like this with a simple asp.net file upload control and a button for upload the excel to the gridview.


After binding the excel using the "Upload" button the gridview will be visible and it will look like this.