Wednesday 28 December 2011

Download PDF file using code


string str_FilePath = Server.MapPath("UploadedFiles/test.pdf");
System.IO.StreamReader sr = new System.IO.StreamReader(str_FilePath);
Response.BufferOutput = true;
Response.AppendHeader("content-disposition", "attachment; filename=test.pdf");
Response.ContentType = "application/pdf";
Response.TransmitFile(str_FilePath);

Copy and paste the above code in button_click event. When you will click the button test.pdf will be downloaded.

Assign QueryString Value to Control in Design Page

<a href="Default.aspx?RollNo=<%=HttpUtility.HtmlEncode(Request.QueryString["RN"]) %>&Cl=<%=HttpUtility.HtmlEncode(Request.QueryString["Cl"]) %>">Click Here</a>

Saturday 24 December 2011

Check Floating point value using JS


<asp:TextBox ID="txtYearValue" runat="server" onkeyup=" isNFloat (event)"></asp:TextBox>

function isNFloat(e)
{
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
var keyCode = (isNN) ? e.which : e.keyCode;
//alert(keyCode);
if (isNN)
{
if (keyCode == 0)
return true;
}
if((keyCode>47&&keyCode<58)||(keyCode==8)||(keyCode==9)||(keyCode==110)||(keyCode==46))
{
return true;
}
else
{
if (e.returnValue)
{
e.returnValue = false;
return false;
}
else if (e.preventDefault)
{
e.preventDefault();
return false;
}
this.event.returnValue = false;
return false;          
}
}

Saturday 17 December 2011

Check DateTime format using JS


The below function checks date in mm-dd-yyyy format.


<asp:TextBox ID="txtYearValue" runat="server" onBlur="checkdate(this)"></asp:TextBox>

function checkdate(input)
{
var validformat=/^\d{2}\-\d{2}\-\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("-")[0]
var dayfield=input.value.split("-")[1]
var yearfield=input.value.split("-")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false)
      input.select()
return returnval
}

Saturday 3 December 2011

Response.Redirect Open Page In New Tab


I am going to explain how to open a page in a new tab/window on Button click in asp.net. Suppose the page contains a button called "btnTest" and your requirement is open a specified page in the new tab on the button click then do the following.

<asp:Button ID=”btnTest” runat=”Server” Text=”Test” OnClick=”btnTest_Click”
OnClientClick ="document.forms[0].target = '_blank';"/>

protected void btnTest_Click(object sender, EventArgs e)
{
      Response.Redirect(”New.aspx”);
}

OR

If there is some code to execute on button click and after that you want to open the page in new tab then do the following :

protected void btnTest_Click(object sender, EventArgs e)
{
      .
      .         // Your Code Here
      .
      Response.Write( “<script> window.open( ‘New.aspx’,'_blank' ); </script>”);
      Response.End();
}

OR

If you want to open the page in a new tab as well as pass some values to the specified page using querystring then do the following :

protected void btnTest_Click(object sender, EventArgs e)
{
      .
      .
      .
      string pageurl="Default.aspx?Id=6&RollNo=15";

      Response.Write( “<script> window.open( ‘"+pageurl+"’,'_blank' ); </script>”);
      Response.End();
}

Thursday 24 November 2011

Move to anchor tag after page postback


1. Set MaintainScrollPositionOnPostback="false" in the @Page directive.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default1" Title="Test anchor Page" MaintainScrollPositionOnPostback="false" %>

2. Create a named anchor in the HTML.
<a name="MOVEHERE"></a>

3. Write the follwoing code in the page load.
if (IsPostBack)
{
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);
}

Import/Export data with SQL Server 2005 Express


Go to Run "C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTSWizard.exe"

Thats it.. Now you can transfer data using the DTS wizard.

Follow the below steps if you want to integrate it with the Sql server management studio express UI .
1. Open sql server management studio express.
2. Select Tools -> External Tools
3. Add a Title and Browse C:\Program Files\Microsoft SQL Server\90 \DTS\Binn\DTSWizard.exe for the Command field.
3. Click OK

Friday 28 October 2011

Remove Item from Drop Down List using JS


<script type="text/javascript">
function removeListItem()
{
      var htmlSelect=document.getElementById('selectYear');
      if(htmlSelect.options.length==0)
     {
           alert('You have removed all options');
            return false;
      }
      var optionToRemove=htmlSelect.options.selectedIndex;
      htmlSelect.remove(optionToRemove);
      alert('The selected option haas been removed successfully');
      return true;
}


<asp:DropDownList ID="selectYear" runat="server">
<asp:ListItem Value="2000">2000</asp:ListItem>
<asp:ListItem Value="2001">2001</asp:ListItem>
<asp:ListItem Value="2002">2002</asp:ListItem>
<asp:ListItem Value="2003">2003</asp:ListItem>
<asp:ListItem Value="2004">2004</asp:ListItem>

</asp:DropDownList>

<input name="btnRemoveItem" type="button" id="btnRemoveItem" value="Remove Option" onClick="javascript:removeListItem();" />


Add value to the Drop Down List using JS


function addNewListItem()
{
     var htmlSelect = document.getElementById('selectYear');
     var optionValue = document.getElementById('txtYearValue');
     var optionDisplaytext = document.getElementById('txtYearDisplayValue');
     if (optionValue.value == '' || isNaN(optionValue.value))
    {
          alert('please enter option value');
           optionValue.focus();
           return false;
    }
    if (optionDisplaytext.value == '' || isNaN(optionDisplaytext.value))
   {
          alert('please enter option display text');
          optionDisplaytext.focus();
          return false;
   }
    if (isOptionAlreadyExist(htmlSelect, optionValue.value))
   {
          alert('Option value already exists');
          optionValue.focus();
          return false;
    }
    if (isOptionAlreadyExist(htmlSelect, optionDisplaytext.value))
    {
          alert('Display text already exists');
          optionDisplaytext.focus();
          return false;
     }
      var selectBoxOption = document.createElement("option");
      selectBoxOption.value = optionValue.value;
      selectBoxOption.text = optionDisplaytext.value;
       htmlSelect.options.add(selectBoxOption);
      alert("Option has been added successfully");
      return true;
}

function isOptionAlreadyExist(listBox, value)
 {
       for (var x = 0; x < listBox.options.length; x++)
      {
                if (listBox.options[x].value == value || listBox.options[x].text == value)
                {
                       return true;
                }
       }
       return false;
}

</script>

<asp:DropDownList ID="selectYear" runat="server">
    <asp:ListItem Value="2000">2000</asp:ListItem>
    <asp:ListItem Value="2001">2001</asp:ListItem>
    <asp:ListItem Value="2002">2002</asp:ListItem>
    <asp:ListItem Value="2003">2003</asp:ListItem>
    <asp:ListItem Value="2004">2004</asp:ListItem>
</asp:DropDownList>

Option Value
<asp:TextBox ID="txtYearValue" runat="server"></asp:TextBox>
Option Display Text
<asp:TextBox ID="txtYearDisplayValue" runat="server"></asp:TextBox>
<input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javascript:addNewListItem();" />

Monday 24 October 2011

Select and Deselect Checkbox with in gridview using Javascript


<asp:GridView ID="gdvShowData" runat="server" AutoGenerateColumns="False" CssClass="gdvBody" Width="100%" >
<Columns>
   <asp:TemplateField>
       <HeaderTemplate>
               <asp:CheckBox ID="chkheader" runat="server"  onclick="Calculate(this);" ToolTip="Check to select all rows"/>
       </HeaderTemplate>
       <ItemTemplate>
               <asp:CheckBox ID="chkchild" runat="server" />
       </ItemTemplate>
   <ItemStyle Width="8%" />
</asp:TemplateField>        
    <asp:BoundField HeaderText="Name" DataField="Name" />            
 </Columns>
 <EmptyDataTemplate>
    There is no record.
 </EmptyDataTemplate>
</asp:GridView>


function Calculate(SelectAllCheckBox)
{
        var chkAll=document.getElementById(SelectAllCheckBox.id);
        var Parentgrid = document.getElementById('<%= gdvShowData.ClientID %>');      
        var items = Parentgrid.getElementsByTagName('input');
        for (i = 1; i < items.length; i++)
        {          
            if (items[i].type == "checkbox")
            {              
                if (chkAll)
                 items[i].checked = chkAll.checked;              
            }
        }
}

function Selectchildcheckboxes(header)
{
    var ck = header;
    var count = 0;
    var gvcheck = document.getElementById('gdvShowData');
    var headerchk = document.getElementById(header);
    var rowcount = gvcheck.rows.length;
    for (i = 1; i < gvcheck.rows.length; i++)
   {
       var inputs = gvcheck.rows[i].getElementsByTagName('input');
       if (inputs[0].checked)
      {
            count++;
       }
    }
     if (count == rowcount-1)
    {
           headerchk.checked = true;
     }
    else
    {
           headerchk.checked = false;
     }
}

protected void gdvShowData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox headerchk = (CheckBox)gdvShowData.HeaderRow.FindControl("chkheader");
CheckBox childchk = (CheckBox)e.Row.FindControl("chkchild");
childchk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + headerchk.ClientID + "')");
}
}


Tuesday 18 October 2011

How to compare DateTime

function Datevalidate(txtFromdate,txtToDate)
{

   var txtFromdate = document.getElementById(txtFromdate);
   var txtToDate = document.getElementById(txtToDate);

   if(txtFromdate.value!="" || txtToDate.value!="")
  {
        var str1 = txtFromdate.value;
        var str2 = txtToDate.value;
        var dt1  = parseInt(str1.substring(0,2),10);
        var mon1 = parseInt(str1.substring(3,5),10);
        var yr1  = parseInt(str1.substring(6,10),10);
        var dt2  = parseInt(str2.substring(0,2),10);
        var mon2 = parseInt(str2.substring(3,5),10);
        var yr2  = parseInt(str2.substring(6,10),10);
        var date1 = new Date(yr1, mon1, dt1);
        var date2 = new Date(yr2, mon2, dt2);     
        if(date2 < date1)
        {
            alert("To Date cannot be lesser than From Date");
            return false;
        }  
    }
}

Monday 10 October 2011

Enable disable button on checkbox check


function hideOnCheck()
{
   var chk = document.getElementById('<%=chk.ClientID%>');
   var btn = document.getElementById('<%=btnSubmit.ClientID%>');
   if (chk && btn)
   {
      if (chk.checked == true)
      {
         btn.disabled = false;
      }
      else
      {
         btn.disabled = true;
      }
    }
}

<asp:CheckBox ID="chk" runat="server" Text="All the above data are correct" onclick="hideOnCheck();"/>

Hide row by selecting radio button option


function setRowonClick()
{
    var rowOther = document.getElementById('<%=trShowDetail.ClientID%>');
    if (rowOther)
   {
        var s = document.getElementById('<%=rbtnIsPS.ClientID%>');
        var s1 = s.getElementsByTagName('input');
        for (var i = 0; i < s1.length; i++)
       {
            if (s1[i].checked)
           {
                  if (s1[i].checked && s1[i].value == '0')
                 {
                      rowOther.style.display = '';
                 }
                 else
                 {
                     rowOther.style.display = 'none';
                 }
             }
          }
     }
}

<asp:RadioButtonList ID="rbtnIsPS" runat="server" RepeatDirection="Horizontal" onclick="setRowonClick();">

Dropdownlist validate


function OnSelectedIndexChange()
{
   var s = document.getElementById('<%=ddlPosition.ClientID%>');
   if (s.value == '0')     // or  if (s.options[s.selectedIndex].text=='select')
   {
      alert("Please select the different option.");
      return false;
   }
   else
      return true;
}

<asp:DropDownList ID="ddlPosition" runat="server" onchange="OnSelectedIndexChange();"/>

Allow only numbers in textbox


function isNNumeric(e)
{
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
var keyCode = (isNN) ? e.which : e.keyCode;
//alert(keyCode);
if (isNN)
{
if (keyCode == 0)
return true;
}
if((keyCode>47&&keyCode<58)||(keyCode==8)||(keyCode==9))
{
return true;
}
else
{
if (e.returnValue)
{
e.returnValue = false;
return false;
}
else if (e.preventDefault)
{
e.preventDefault();
return false;
}
this.event.returnValue = false;
return false;          
}
}


  <asp:TextBox ID=”txt_maxage” Onkeypress=”return isNumberKey(event)” runat=”server”></asp:TextBox>

Tuesday 20 September 2011

How to print notepad content in asp.net page

If you want to print the notepad content in the aspx page then you can do in the following ways.

Step-1 :  Take a lable on the page.
Step-2 : In the aspx.cs file add the in the above.
                          using System.IO;
Step-3 : In the page load write the following
         
              lblReadContent.Text = ReadFile(Server.MapPath("~/articles.txt"));
Step-4 : Create a function ReadFile which will return string.        
              public string ReadFile(string strFileName)
             {    
                  StreamReader fp=null;
                  string returnText;
                  try
                 {
                           fp = File.OpenText(strFileName);
                           returnText= fp.ReadToEnd();
                           fp.Close();
                 }
                catch
                {
                          returnText = "";
                }
                return returnText;
      }


Sunday 18 September 2011

Delete duplicate rows


SET ROWCOUNT 1
delete emp from emp a where (select count(*) from emp b where a.name=b.name) >1
WHILE @@rowcount > 0
delete emp from emp a where (select count(*) from emp b where a.name=b.name) >1
SET ROWCOUNT 0

or


DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

or



WITH empTable as
(
SELECT ROW_NUMBER() Over(PARTITION BY EmpName,Position ORDER BY EmpName) As RowNumber,* FROM emp
)
DELETE FROM  empTable  where RowNumber >1
SELECT * FROM emp order by Id asc

Display row by Radio button selected change


function DisplayRowonRbl()
{     
     var trDesignation= document.getElementById('<%=trDesignation.ClientID%>');
     var tblDepartment= document.getElementById('<%=tblDepartment.ClientID%>');
      var s=document.getElementById('<%=rbnDepartment.ClientID%>');
      var s1=s.getElementsByTagName('input');
      for (var i = 0; i < s1.length; i++)
      {
          if (s1[i].checked && s1[i].value=='Others')
          {
                trDesignation.style.display = '';
                tblDepartment.style.display = 'none';
           }
           else
           {
                  tblDepartment.style.display = '';
                  trDesignation.style.display = 'none';
                 }
            }
   }

Call the above method on the selected change properties of radiobutton.

Friday 9 September 2011

Open a new window in pop up with print option


Call the below function in the OnClientClick of the button.

<script language="javascript">
function Clickheretoprint()
{
  var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
      disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
  var content_vlue = document.getElementById("print_content").innerHTML;
 
  var docprint=window.open("","",disp_setting);
   docprint.document.open();
   docprint.document.write('<html><head><title>Home Page</title>');
   docprint.document.write('</head><body onLoad="self.print()"><center>');        
   docprint.document.write(content_vlue);        
   docprint.document.write('</center></body></html>');
   docprint.document.close();
   docprint.focus();
}
</script>

Friday 19 August 2011

Non Clustered indexes per tabel


In Sql Server 2008 32 Bit addition ,following are the limit for Non Cluster Index and Cluster Index

Clustered indexes per table: 1

None clustered per table: 999

Nested sub queries: 32

Nested trigger levels: 32

Parameters per stored procedure: 2100

Parameters per user-defined function: 210

Best way to display default image if specified image file is not found ?


Many times in grid/repeater or even in image display we have a problem if we don’t find any image related to that ID/Record and to replace “X” sign or image not found message we need to do programming but here is the
Quick solution which saves lot’s of your time and also your server processing time.
Just put following code in your in your image control.


onerror="this.onerror=null;this.src='Noview.jpg'">

Thursday 4 August 2011

How to call javascript code from server side

One can call JavaScript client side function directly from code behind using RegisterStartupScript. If one wants JavaScript to be embedded into codebehind, then make use of RegisterClientScriptBlock:
<script>
function fnShowMessage()
{
       alert(" Invoke Javascript function from Server Side Code Behind ");
 }
 </script>
protected void Button1_Click(object sender, EventArgs e)
{
        ClientScript.RegisterStartupScript (GetType(),"Javascript", "javascript: fnShowMessage(); ",true);
}
protected void Button2_Click(object sender, EventArgs e)
{
       ClientScript.RegisterClientScriptBlock(GetType(), "Javascript",  "<script>alert('Record Added Successfully')</script>");
}


Saturday 16 July 2011

Merge Statement – One Statement for INSERT, UPDATE, DELETE

MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it.
One of the most important advantage of MERGE statement is all the data is read and processed only once. In previous versions three different statement has to be written to process three different activity (INSERT, UPDATE or DELETE), however using MERGE statement all update activity can be done in one pass of database table. This is quite an improvement in performance of database query.
In our example we will consider three main conditions while we merge this two tables.
1.    Delete the records whose marks are more than 250.
2.    Update marks and add 25 to each as internals if records exist.
3.    Insert the records if record does not exists.
Now we will write MERGE process for tables created earlier. We will make sure that we will have our three conditions discussed above are satisfied.
MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetailsAS sd
ON stm.StudentID sd.StudentID
WHEN MATCHED AND stm.StudentMarks 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks stm.StudentMarks 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);

There are two very important points to remember while using MERGE statement.
·         Semicolon is mandatory after the merge statement.
·         When there is a MATCH clause used along with some condition, it has to be specified first amongst all other WHEN MATCH clause.

Monday 4 July 2011

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");
      }
   }


Sunday 29 May 2011

DataTable - Adding, Modifying, Deleting, Filtering, Sorting rows & Reading/Writing from/to Xml

Creating a DataTable

To create a DataTable, you need to use System.Data namespace, generally when you create a new class or page, it is included by default by the Visual Studio. Lets write following code to create a DataTable object. Here, I have pased a string as the DataTable name while creating DataTable object.

// instantiate DataTable
DataTable dTable = new DataTable("Dynamically_Generated");



Creating Columns in the DataTable

To create column in the DataTable, you need to use DataColumn object. Instantiate the DataColumn object and pass column name and its data type as parameter. Then call add method of DataTable column and pass the DataColumn object as parameter.


// create columns for the DataTable
DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));
dTable.Columns.Add(auto);
// create another column
DataColumn name = new DataColumn("Name", typeof(string));
dTable.Columns.Add(name);
// create one more column
DataColumn address = new DataColumn("Address", typeof(string));
dTable.Columns.Add(address);



Specifying AutoIncrement column in the DataTable

To specify a column as AutoIncrement (naturally it should be an integer type of field only), you need to set some properties of the column like AutoIncrement, AutoIncrementSeed. See the code below, here I am setting the first column "AutoID" as autoincrement field. Whenever a new row will be added its value will automatically increase by 1 as I am specified AutoIncrementSeed value as 1.


// specify it as auto increment field
auto.AutoIncrement = true;
auto.AutoIncrementSeed = 1;
auto.ReadOnly = true;
If you want a particular column to be a unique column ie. you don't want duplicate records into that column, then set its Unique property to true like below.
auto.Unique = true;



Specifying Primary Key column in the DataTable

To set the primary key column in the DataTable, you need to create arrays of column and store column you want as primary key for the DataTable and set its PrimaryKey property to the column arrays. See the code below.


// create primary key on this field
DataColumn[] pK = new DataColumn[1];
pK[0] = auto;
dTable.PrimaryKey = pK;
Till now we have created the DataTable, now lets populate the DataTable with some data.



Populating data into DataTable

There are two ways to populate DataTable.
Using DataRow object
Look at the code below, I have created a DataRow object above the loop and I am assiging its value to the dTable.NewRow() inside the loop. After specifying columns value, I am adding that row to the DataTable using dTable.Rows.Add method.


// populate the DataTable using DataRow object
DataRow row = null;
for (int i = 0; i < 5; i++)
{
     row = dTable.NewRow();
     row["AutoID"] = i + 1;
     row["Name"] = i + " - Ram";
     row["Address"] = "Ram Nagar, India - " + i;
     dTable.Rows.Add(row);
}

Instead of using the column name, you can use ColumnIndex too, however it is not suggested as you might want to add a column in the mid of the table then you will need to change your code wherever you have specified the index of the column. Same applies while reading or writing values into Database column. Asiging the value of column using Arrays In following code, I have specified the values of every column as the array separated by comma (,) in the Add method of the dTable.Rows.

 // manually adding rows using array of values
 dTable.Rows.Add(6, "Manual Data - 1", "Manual Address - 1, USA");
dTable.Rows.Add(7, "Manual Data - 2", "Manual Address - 2, USA");


Modifying data into DataTable


Modifying Row Data To edit the data of the row, sets its column value using row index or by specifying the column name. In below example, I am updating the 3rd row of the DataTable as I have specified the row index as 2 (dTable.Rows[2]).

 // modify certain values into the DataTable
dTable.Rows[2]["AutoID"] = 20;
dTable.Rows[2]["Name"] = "Modified";
dTable.Rows[2]["Address"] = "Modified Address";
dTable.AcceptChanges();


Deleting Row


To delete a row into DataTable, call the rows.Delete() method followed by AcceptChanges() method. AcceptChanges() method commits all the changes made by you to the DataTable. Here Row[1] is the index of the row, in this case 2nd row will be deleted as in collection (here rows collection) count start from 0.

// Delete row
 dTable.Rows[1].Delete();
dTable.AcceptChanges();


Filtering data from DataTable

To filter records from the DataTable, use Select method and pass necessary filter expression. In below code, the 1st line will simply filter all rows whose AutoID value is greater than 5. The 2nd line of the code filters the DataTable whose AutoID value is greater than 5 after sorting it.

DataRow[] rows = dTable.Select(" AutoID > 5");
DataRow[] rows1 = dTable.Select(" AutoID > 5", "AuotID ASC");

Note that Select method of the DataTable returns the array of rows that matche the filter expression. If you want to loop through all the filtered rows, you can use foreach loop as shown below. In this code, I am adding all the filtered rows into another DataTable.

foreach (DataRow thisRow in rows)
{
// add values into the datatable
dTable1.Rows.Add(thisRow.ItemArray);
}

Working with Aggregate functions 

We can use almost all aggregate functions with DataTable, however the syntax is bit different than standard SQL.
Suppose we need to get the maximum value of a particular column, we can get it in the following way.

DataRow[] rows22 = dTable.Select("AutoID = max(AutoID)");
string str = "MaxAutoID: " + rows22[0]["AutoID"].ToString();

To get the sum of a particular column, we can use Compute method of the DataTable. Compute method of the DataTable takes two argument. The first argument is the expression to compute and second is the filter to limit the rows that evaluate in the expression. If we don't want any filteration (if we need only the sum of the AutoID column for all rows), we can leave the second parameter as blank ("").

object objSum = dTable.Compute("sum(AutoID)", "AutoID > 7");
string sum = "Sum: " + objSum.ToString();
// To get sum of AutoID for all rows of the DataTable
object objSum = dTable.Compute("sum(AutoID)", "");



Sorting data of DataTable

Oops !. There is no direct way of sorting DataTable rows like filtering (Select method to filter DataRows).
There are two ways you can do this.

Using DataView
See the code below. I have created a DataView object by passing my DataTable as parameter, so my DataView will have all the data of the DataTable. Now, simply call the Sort method of the DataView and pass the sort expression. Your DataView object have sorted records now, You can either directly specify the Source of the Data controls object like GridView, DataList to bind the data or if you need to loop through its data you can use ForEach loop as below.

// Sorting DataTable
DataView dataView = new DataView(dTable);
dataView.Sort = " AutoID DESC, Name DESC";
foreach (DataRowView view in dataView)
{
Response.Write(view["Address"].ToString());
}

Using DataTable.Select() method
Yes, you can sort all the rows using Select method too provided you have not specified any filter expression. If you will specify the filter expression, ofcourse your rows will be sorted but filter will also be applied. A small drawback of this way of sorting is that it will return array of DataRows as descibed earlier so if you are planning to bind it to the Data controls like GridView or DataList you will have for form a DataTable by looping through because directly binding arrays of rows to the Data controls will not give desired results.

DataRow[] rows = dTable.Select("", "AutoID DESC");
Writing and Reading XmlSchema of the DataTable
If you need XmlSchema of the DataTabe, you can use WriteXmlSchema to write and ReadXmlSchema to read it. There are several overloads methods of both methods and you can pass filename, stream, TextReader, XmlReader etc. as the parameter. In this code, the schema will be written to the .xml file and will be read from there.

// creating schema definition of the DataTable
dTable.WriteXmlSchema(Server.MapPath("~/DataTableSchema.xml"));
// Reading XmlSchema from the xml file we just created
DataTable dTableXmlSchema = new DataTable();
dTableXmlSchema.ReadXmlSchema(Server.MapPath("~/DataTableSchema.xml"));



Reading/Writing from/to Xml

If you have a scenario, where you need to write the data of the DataTable into xml format, you can use WriteXml method of the DataTable. Note that WriteXml method will not work if you will not specify the name of the DataTable object while creating it. Look at the first code block above, I have passed "Dynamically_Generated" string while creating the instance of the DataTable. If you will not specify the name of the DataTable then you will get error as WriteXml method will not be able to serialize the data without it.

// Note: In order to write the DataTable into XML,
// you must define the name of the DataTable while creating it
// Also if you are planning to read back this XML into DataTable, you should define the   XmlWriteMode.WriteSchema too
// Otherwise ReadXml method will not understand simple xml file
dTable.WriteXml(Server.MapPath("~/DataTable.xml"), XmlWriteMode.WriteSchema);
// Loading Data from XML into DataTable
DataTable dTableXml = new DataTable();
dTableXml.ReadXml(Server.MapPath("~/DataTable.xml"));

If you are planning to read the xml you have just created into the DataTable sometime later then you need to specify XmlWriteMode.WriteSchema too as the 2nd parameter while calling WriteXml method of the DataTable otherwise normally WriteXml method doesn't write schema of the DataTable. In the abscence of the schema, you will get error (DataTable does not support schema inference from Xml) while calling ReadXml method of the DataTable.