Next[UP] and Previous[Down] Button in ListView

In This Example we can Traverse the listview item up and down or Next and Previous.
Lets Start Step by Step.

Step 1 : Creating a Window Application.

Step 2 : Drag and Drop 3 Controls in Default page from Toolbox
1- ListView (Name=”listView1″)
2- Button (Name=”btnUP”,Text=”UP”)
3- Button (Name=”btnDown”,Text=”DOWN”)
Step 3: double Click on Up and Down Button for Generate the Click Event

Step 4 :Create function for Fill the list View

private void BindListView()
{
string[] array = { “ListItem1”, “ListItem2”, “ListItem3”, “ListItem4”, “ListItem5”, “ListItem6” };
var items = listView1.Items;
foreach (var value in array)
{
items.Add(value);
}
}

Step 5: Do Code for Up and Down Button

// UP Button
 private void btnUP_Click(object sender, EventArgs e)
        {
            int index = listView1.SelectedItems[0].Index;

            if (index < listView1.Items.Count - 1)
            {
                listView1.Select();
                listView1.Items[index + 1].Selected = true;
                btnDown.Enabled = true;
                if ((index = listView1.SelectedItems[0].Index) == listView1.Items.Count - 1)
                    btnUP.Enabled = false;
            }
            else
                btnUP.Enabled = false;
        }
// Down Button
        private void btnDown_Click(object sender, EventArgs e)
        {
            int index = listView1.SelectedItems[0].Index;
            if (index > 0)
            {
                listView1.Select();
                listView1.Items[index - 1].Selected = true;
                btnUP.Enabled = true;
                if ((index = listView1.SelectedItems[0].Index) == 0)
                    btnDown.Enabled = false;
            }
            else
                btnDown.Enabled = false; 
        }

Step 6: For Assistance i am Coping all page Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            BindListView();
            listView1.MultiSelect = false;
            listView1.Select();
            listView1.Items[0].Selected = true;  
        }
        private void Form1_Load_1(object sender, EventArgs e)
        {
            
        }

        private void BindListView()
        {
            string[] array = { "ListItem1", "ListItem2", "ListItem3", "ListItem4", "ListItem5", "ListItem6" };
            var items = listView1.Items;
            foreach (var value in array)
            {
                items.Add(value);
            }
        }
        private void btnUP_Click(object sender, EventArgs e)
        {
            int index = listView1.SelectedItems[0].Index;

            if (index < listView1.Items.Count - 1)
            {
                listView1.Select();
                listView1.Items[index + 1].Selected = true;
                btnDown.Enabled = true;
                if ((index = listView1.SelectedItems[0].Index) == listView1.Items.Count - 1)
                    btnUP.Enabled = false;
            }
            else
                btnUP.Enabled = false;
        }
        private void btnDown_Click(object sender, EventArgs e)
        {
            int index = listView1.SelectedItems[0].Index;
            if (index > 0)
            {
                listView1.Select();
                listView1.Items[index - 1].Selected = true;
                btnUP.Enabled = true;
                if ((index = listView1.SelectedItems[0].Index) == 0)
                    btnDown.Enabled = false;
            }
            else
                btnDown.Enabled = false; 
        }


    }
}
Posted in Asp.Net | Leave a comment

Send XML to Procedure and Insert into DATABASE

SomeTimes we have Requirements to insert xml to Database.for this we send the whole xml file as parameter to store procedure.
Lets Start insert Xml Data to Database Step By Step.
for Example we have a sample XML which we want to insert into table.

<Table>
   <Rows fileno="1" filetype="txt" pagecount="10">
    <filename>txtfilename</filename>    
    <source>txtfilesource</source>
  </Rows>
  <Rows fileno="2" filetype="pfd" pagecount="15">
    <filename>pdffilename</filename>
    <source>pdffilesource</source>
  </Rows>
</Table>

Step 1: Create the Table

Create Table tblDemoTable
(
sno   int  identity(1,1),
fileno int,
filetype varchar(10),
pagecount int,
filename varchar(50),
source varchar(50)
)

Step 2: Create Store Procedure

Create PROCEDURE usp_insertXmlToDb
@Xmldata xml
AS
BEGIN
DECLARE @idoc int
EXEC sp_xml_preparedocument @idoc OUTPUT, @xmldata 


 INSERT INTO tblDemoTable                                                                                               
      SELECT                                       
      fileno                                                              
     ,filetype                                                    
     ,pagecount                                                                        
     ,filename                                                                        
     ,source                                                                                                                                             
FROM   OPENXML (@idoc, '/Table/Rows',2)                                                      
     WITH ( fileno int '@fileno',                                                        
     filetype       varchar(10) '@filetype',                             
     pagecount  int '@pagecount',                                                        
     dt  varchar(150) '@dt',                                                                                                              
     filename varchar(50) './filename/text()',                                      
     source varchar(max) './source/text()'                                                                                                            
    )                                            
EXEC sp_xml_removedocument @idoc 
END

Step 3: Execure the Store Procedure

usp_insertXmlToDb'<Table>
   <Rows fileno="1" filetype="txt" pagecount="10">
    <filename>txtfilename</filename>    
    <source>txtfilesource</source>
  </Rows>
  <Rows fileno="2" filetype="pfd" pagecount="15">
    <filename>pdffilename</filename>
    <source>pdffilesource</source>
  </Rows>
</Table>'

Step 4: check the Table Data

select * from tblDemoTable
Posted in Asp.Net, Sql | Tagged , | Leave a comment

Create XML File at runtime using CSharp

There are many advantages to using XML for information exchange, and they offer many benefits to the user.
In this Example i am describing how to Create a Xml file dynamically using C#.

Step1
Create a function for generating Xml Document

// xmlpath = D:/xmlfolder
   private void CreateXmlFile(string xmlpath)
        {
            string xmlfilepath = xmlpath + @"\" + "xmlsample.xml";
            if (!System.IO.Directory.Exists(xmlpath  + @"\"))
            {
                System.IO.Directory.CreateDirectory(xmlpath  + @"\");
            }
            if (!System.IO.File.Exists(xmlfilepath ))
            {
                using (var file = System.IO.File.Create(xmlfilepath)) ;
            }
            using (XmlTextWriter myXmlWriter = new XmlTextWriter(xmlfilepath, null))
            {
                myXmlWriter.Formatting = Formatting.Indented;
                myXmlWriter.Indentation = 4;
                myXmlWriter.WriteStartElement("issues");
                int i = 0;
                for (i = 1; i <= 5; i++)
                {
                myXmlWriter.WriteStartElement("job");// see next line
                myXmlWriter.WriteAttributeString("dt", "");
                myXmlWriter.WriteAttributeString("mid", "");
                myXmlWriter.WriteAttributeString("shipment", "");
                myXmlWriter.WriteAttributeString("name", "Ashish + i");
                myXmlWriter.WriteElementString("sername", "Sharma + i");
                }
                myXmlWriter.WriteEndElement();
                myXmlWriter.Flush();
                myXmlWriter.Close();
            }
        }

Output XML will be

<?xml version="1.0"?>
<issues>
<job name="ashish1" shipment="" mid="" dt="">
 <sername>sharma1</sername> 
</job>
<job name="ashish2" shipment="" mid="" dt="">
 <sername>sharma2</sername> 
</job>
.
.
.
.
.
.
.
.
 </issues>

Posted in Grid View | Leave a comment

Merge PDF pages into One PDF Document in Csharp(Pdf Sharp dll)

In my previous post i have explain how to splite pdf documents

Some times we have requirement to Merge PDF document into one PDF Documents.
In this Article i am explaining how to merge pdf document into one.
For this i used pdfSharp dll which is free available into internet.
i am describing this example step by step.

Step 1(Create new Project)
Open Visual Studio
Go to File–>New–>Project

Go to Window Form Application and Give the “Mergepdfdoc” name to the project.

a new Form is showing right Click on Window Form and select View Code.
Step 2
put your inputpdf1.pdf,inputpdf2.pdf……….(you can choose another name) into debug folder of your project.
output file will also created in debug folder of your project.
Step 3
dowonload PdfSharp.dll from internet.
now add the reference of this dll to your project.
Right click on your solution Explorer–> Add Reference –>Browse(browse the downloaded dll path)–> ok
now add the button control on your page.
Drag and Drop the Button Control from the Toolbar and name it “btnmergepdf”.
double click on button and generate the OnClick Event.
step 4>
Create a function for Merging the pdf documents

        private static void MergeMultiplePDFIntoSinglePDFDoc(string outputpdfFilePath, string[] pdfFilescoll)
        {
            //create a new pdf output document
            PdfDocument outputPDFDocument = new PdfDocument();
            //loop for reading input pdf files 
            foreach (string pdfFile in pdfFilescoll)
            {
                PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
                outputPDFDocument.Version = inputPDFDocument.Version;
                //loop for reading all pages of input files
                foreach (PdfPage page in inputPDFDocument.Pages)
                {
                    // adding the input pages into output pdf documents
                    outputPDFDocument.AddPage(page);
                }
            }
             // At last save the output document
            outputPDFDocument.Save(outputpdfFilePath);
        }

Step 5
call the MergeMultiplePDFIntoSinglePDFDoc function into onClick event of btnmergepdf

        private void btnmergepdf_Click(object sender, EventArgs e)
        {
         string outputpdffilename = "mynewpdf.pdf";
         string[] Collofinputddffiles = {"inputpdf1.pdf","inputpdf2.pdf","inputpdf3.pdf"};
         MergeMultiplePDFIntoSinglePDFDoc(outputpdffilename ,Collofinputddffiles );
        }
Posted in Grid View | Leave a comment

Splite PDF document using Csharp(pdf Sharp dll)

Some times we have requirement to Splite PDF document into several PDF Documents.
In this Article i am explaining how to Splite Large pdf document.
For this i used pdfSharp dll which is free available into internet.
i am describing this example step by step.

Step 1(Create new Project)
Open Visual Studio
Go to File–>New–>Project

Go to Window Form Application and Give the “SplitPdfDoc” name to the project.

a new Form is showing right Click on Window Form and select View Code.

Step 2
dowonload PdfSharp.dll from internet.
now add the reference of this dll to your project.
Right click on your solution Explorer–> Add Reference –> Browse(browse the downloaded dll path)–> ok
now add the button control on your page.
Drag and Drop the Button Control from the Toolbar and name it “btnsplitepdf”.
double click on button and generate the OnClick Event.

Step 3
put your input.pdf(you can choose another name) into debug folder of your project.
output file will also created in debug folder of your project.

Go to CodeBehind and copy paste the following code within button Onclick Event.

        private void btnsplitepdfdoc_Click(object sender, EventArgs e)
        {
            // input pdf file name
            string inputfile = "input.pdf";
            // read the pdf document
            PdfDocument inputPDFDocument = PdfReader.Open(inputfile, PdfDocumentOpenMode.Import);
           // get pdf file name without .pdf extension
            string filenamewoext = Path.GetFileNameWithoutExtension(inputfile);
            // loop for spliting the pdf document on the bases of pageIndex
            for (int pageIndex = 0; pageIndex < inputPDFDocument.PageCount; pageIndex++)
            {
                // create new output pdf document
                PdfDocument outpdfdoc = new PdfDocument();
                outpdfdoc.Version = inputPDFDocument.Version;
                outpdfdoc.Info.Title =
                  String.Format("Page {0} of {1}", pageIndex + 1, inputPDFDocument.Info.Title);
                outpdfdoc.Info.Creator = inputPDFDocument.Info.Creator;
 
                // Add the page
                outpdfdoc.AddPage(inputPDFDocument.Pages[pageIndex]);
                // save the new output page
                outpdfdoc.Save(String.Format("{0}-{1}.pdf", filenamewoext, pageIndex + 1));

        }
    }
Posted in Asp.Net | 1 Comment

Merge GridView Header

protected void grvMergeHeader_RowCreated
(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow =
new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = “Department”;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = “Employee”;
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

grvMergeHeader.Controls[0].Controls.AddAt
(0, HeaderGridRow);

}
}
}

Posted in Grid View | 2 Comments

Read Attributes and Elements of XML Documents

    public void ReadAEOfXml()
    {

        XmlTextReader xtr = new XmlTextReader("D:/mapping1.xml");
        while(xtr.Read())
        {
            XmlNodeType xmlnotetype = xtr.NodeType;
            switch (xmlnotetype)
            { 
                case XmlNodeType.Element :
                    Response.Write(string.Format("Element name= {0}",xtr.Name) + "</BR>");
                    if (xtr.HasAttributes)
                    {
                        for (int i = 0; i < xtr.AttributeCount; i++)
                        {
                            xtr.MoveToAttribute(i);
                            Response.Write(string.Format("Element is {0} and Attributes is: {1}", xtr.Name, xtr.Value) + "</BR>");
                        }
                    
                    }
                 break;
                case XmlNodeType.Text:
                 Response.Write(string.Format("value is {0}", xtr.Value) + "</BR>");
                 break;
           
            }
 
        }
   
    }
Posted in Asp.Net | Tagged | Leave a comment

GridView Column total on onBlur event using Javascript

GridView Column total on onBlur event using Javascript.
null
It is very desire task to show the total of gridview dynamic generate column on Blur or onchnage event using javascript.it is working fine with updatepanel.
so today i am posting this

Step1 – Create GridView

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
            onrowdatabound="GridView1_RowDataBound">
        <Columns>
        
 <asp:TemplateField HeaderText="col1">
<ItemTemplate>
<asp:TextBox ID="txtcol1" Text='<%#Eval("id1") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField>
 
  <asp:TemplateField HeaderText="col2">
<ItemTemplate>
<asp:TextBox ID="txtcol2" Text='<%#Eval("id2") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField>
 
        </Columns>
        </asp:GridView>

Step2 – cearte Javascript function

    function JvfunonBlur()
    {
      var grid = document.getElementById('<%=GridView1.ClientID %>');
        var col1;
        var totalcol1 = 0;

        var col2;
        var totalcol2 = 0; 
        
          
        for (i = 0; i < grid.rows.length; i++) 
        {
            col1 = grid.rows[i].cells[0];
            col2 = grid.rows[i].cells[1];
            
             for (j = 0; j < col1.childNodes.length; j++) 
             {
                if (col1.childNodes[j].type == "text")
                 {
                 if(!isNaN(col1.childNodes[j].value) &&  col1.childNodes[j].value != "")
                     {
                        totalcol1 += parseInt(col1.childNodes[j].value)
                     }
                }
             }
            
             for (j = 0; j < col2.childNodes.length; j++)
             {
                if (col2.childNodes[j].type == "text")
                 {
                     if(!isNaN(col2.childNodes[j].value) &&  col2.childNodes[j].value != "")
                     {
                        totalcol2 += parseInt(col2.childNodes[j].value)
                     }
                }
            }
        }
        document.getElementById('<%=txttotal1.ClientID %>').value = totalcol1;
        document.getElementById('<%=txttotal2.ClientID %>').value = totalcol2;
    }
    

Step3 – Call this javascript function on OnRowDataBound on csharp code

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txt = (TextBox)e.Row.FindControl("txtcol1");
            txt.Attributes.Add("onBlur", "JvfunonBlur();");

            TextBox txt1 = (TextBox)e.Row.FindControl("txtcol2");
            txt1.Attributes.Add("onBlur", "JvfunonBlur();");
        
        }

Whole Code At Once

.Aspx Page

<%@ 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>Untitled Page</title>
    <script type="text/javascript">
    function JvfunonBlur()
    {
      var grid = document.getElementById('<%=GridView1.ClientID %>');
        var col1;
        var totalcol1 = 0;

        var col2;
        var totalcol2 = 0; 
        
          
        for (i = 0; i < grid.rows.length; i++) 
        {
            col1 = grid.rows[i].cells[0];
            col2 = grid.rows[i].cells[1];
            
             for (j = 0; j < col1.childNodes.length; j++) 
             {
                if (col1.childNodes[j].type == "text")
                 {
                 if(!isNaN(col1.childNodes[j].value) &&  col1.childNodes[j].value != "")
                     {
                        totalcol1 += parseInt(col1.childNodes[j].value)
                     }
                }
             }
            
             for (j = 0; j < col2.childNodes.length; j++)
             {
                if (col2.childNodes[j].type == "text")
                 {
                     if(!isNaN(col2.childNodes[j].value) &&  col2.childNodes[j].value != "")
                     {
                        totalcol2 += parseInt(col2.childNodes[j].value)
                     }
                }
            }
        }
        document.getElementById('<%=txttotal1.ClientID %>').value = totalcol1;
        document.getElementById('<%=txttotal2.ClientID %>').value = totalcol2;
    }
    
    
    </script>
</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" AutoGenerateColumns="false" 
            onrowdatabound="GridView1_RowDataBound">
        <Columns>
        
 <asp:TemplateField HeaderText="col1">
<ItemTemplate>
<asp:TextBox ID="txtcol1" Text='<%#Eval("id1") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField>
 
  <asp:TemplateField HeaderText="col2">
<ItemTemplate>
<asp:TextBox ID="txtcol2" Text='<%#Eval("id2") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField>
 
        </Columns>
        </asp:GridView>
       
        Total
         <br />
        <asp:TextBox ID="txttotal1" runat="server"></asp:TextBox>
        <asp:TextBox ID="txttotal2" runat="server"></asp:TextBox>
        <br />
        
    </ContentTemplate>
    </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

.C# Code

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

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

    }
    private void FillGrid()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("id1", typeof(int));
        dt.Columns.Add("id2", typeof(int));
        dt.Rows.Add(0, 0);
        dt.Rows.Add(0, 0);

        GridView1.DataSource = dt;
        GridView1.DataBind();
        
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txt = (TextBox)e.Row.FindControl("txtcol1");
            txt.Attributes.Add("onBlur", "JvfunonBlur();");

            TextBox txt1 = (TextBox)e.Row.FindControl("txtcol2");
            txt1.Attributes.Add("onBlur", "JvfunonBlur();");
        
        }
    }
}

Posted in Asp.Net, Grid View, JavaScript | 7 Comments

Transaction in Ado.Net

Transaction is the collection of Commands. Transaction work on nothing or All function.

Means if a command fails then all command fails .

Steps to Put Transaction in Ado.net
Setp1 : create the sqlTransaction object
Step 2: Define the Connection property. And set the BeginTransaction() function with Connection object.
Step3: write the Sql Commands
Step4: pass transaction object in command()
Step5: commit()/Rollback Transaction
For Example

//create your connection property first
SqlTransaction st;
SqlCommand cmd;
con.Open();
st = con.BeginTransaction();
try
{
cmd = new SqlCommand("Insert into A (id,Fname) values (1,'aashish')", con,st);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("Insert into B (id1,Lname) values (1,'aashish')", con,st);
cmd.ExecuteNonQuery();
 st.Commit();
}
catch
{
 st.Rollback();
}


Posted in Asp.Net, Sql | Leave a comment

Age Calculate using Sql Query(Age Function in sql)

Step1 – Create Function fn_GetAge

 

 


set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

&nbsp;

ALTER FUNCTION [dbo].[fn_GetAge]

(@DOB as datetime, @now as datetime)

returns int

as

BEGIN

DECLARE @age INT

IF(@DOB IS NOT NULL)

BEGIN

SELECT @age =

CASE WHEN MONTH(@DOB) &gt; MONTH(@now)

THEN DATEDIFF(YYYY,@DOB,@now)-1

WHEN MONTH(@DOB) &lt; MONTH(@now)

THEN DATEDIFF(YYYY,@DOB, @now)

WHEN MONTH(@DOB) = MONTH(@now)

THEN

CASE WHEN DAY(@DOB) &gt; DAY(@now)

THEN DATEDIFF(YYYY, @DOB, @now) - 1

ELSE

DATEDIFF(YYYY,@DOB, @now)

END

END

END

ELSE

SELECT @age = 0

RETURN @age

END

 

 

 

Step 2: Call this Functin

 


select dbo.[fn_GetAge]('1946-05-05','2011-03-13')

 

Posted in Sql | Leave a comment