Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday 25 June 2015

Use of ? in C#

You might be using ? in your code many times but when it gets specifically asked what is the use of ?
in C# then sometimes you not able to recall which makes this as an interview question.
Coming to the answer. Below are soem usage of "?" in C#

Nullable type :
To declare a nullable type ? is gets used.
e.g.
    int? num = null;

Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct
range of values for its underlying value type, plus an additional null value.

?? Operator (null-coalescing operator) which returns the left-hand operand if the operand is not null;
otherwise it returns the right hand operand. It mostly gets used with nullable types.   
int? x = null;
int y = x ?? -1;

In above example if x is null then y will have -1 value else x's value.

Conditional operator (?:)
? gets used in conditional operator which returns one of two values depending on the value of a Boolean expression.
   
int i = 6;
string str = (i >3 ? "yes": "no");

In above example conditional operator is used. So if i > 3 condition is true str will have value "yes" else value "no"

What is difference of int and uint?

Both int and uint are 32 bit integral types the difference is int is signed integral and uint is a unsigned integral i.e. int can have both negative and postive integral values but uint always has positive values in a range of 0 to 4,294,967,295.

Tuesday 23 June 2015

Implement Mutually Exclusive CheckBoxList (CheckBoxes) inside GridView in ASP.Net

Mutually exclusive CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.

 HTML Markup
The following HTML Markup consists of a GridView with two BoundField columns and a TemplateField column containing an ASP.Net CheckBoxList control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
        <asp:TemplateField HeaderText="Gender" ItemStyle-Width="150">
            <ItemTemplate>
                <asp:CheckBoxList ID = "chkGender" runat="server" RepeatDirection = "Horizontal">
                    <asp:ListItem Text="Male" Value="M" />
                    <asp:ListItem Text="Female" Value="F" />
                </asp:CheckBoxList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>


protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Id"), new DataColumn("Gender"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "M", "Sujoy Santra", "India");
        dt.Rows.Add(2, "M", "Sumit Kumar Sen", "Brazil");
        dt.Rows.Add(3, "F", "Soumi Santra", "India");
        dt.Rows.Add(4, "M", "Mithun Patra", "Canada");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}







 Populating the Selected Value of CheckBoxList in GridView
Inside the OnRowDataBound event handler of GridView, first the value of Gender is determined from the DataItem object of the GridView.
Finally the CheckBoxList is referenced using the FindControl method and its selected value is set.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string gender = (e.Row.DataItem as DataRowView)["Gender"].ToString();
        CheckBoxList chkGender = (e.Row.FindControl("chkGender") as CheckBoxList);
        chkGender.Items.FindByValue(gender).Selected = true;
    }
}

 Implement Mutually Exclusive CheckBoxList (CheckBoxes) inside GridView
Inside the jQuery document ready event handler, a click event handler is assigned to each CheckBox of all the CheckBoxLists present inside the GridView.
When a CheckBox is clicked in a CheckBoxList, all the CheckBoxes except the current are unchecked.
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=chkGender] input").click(function () {
            $(this).closest("table").find("input").not(this).removeAttr("checked");
        });
    });
</script>

Thursday 11 June 2015

Use ViewState in diffrent page



If you want to use only viewstate to send data to next page, then you should use the server.transfer() method instead of resposnse.redirect() method. Let us suppose we want to pass viewstate on click of a button as below:

    public void btnSer_OnClick(object sender, EventArgs e)
    {

        ViewState["yourvalue"] = "sujoy santra";
        ViewState["yourcity"] = "kolkata";
        Server.Transfer("Default.aspx");

    }

on the same page create a method of the class statebag

     public StateBag ReturnViewState()
    {
        return ViewState;
    }

Now on the page where you want to transfer let here be Default.aspx. Place the following function in Default.aspx.cs file

private StateBag PreviousPageViewState
    {
        get
        {
            StateBag returnValue = null;
            if (PreviousPage != null)
            {
                Object objPreviousPage = (Object)PreviousPage;
                MethodInfo objMethod = objPreviousPage.GetType().GetMethod("ReturnViewState");//System.Reflection class
                return (StateBag)objMethod.Invoke(objPreviousPage, null);

            }
            return returnValue;
        }
    }

Now let us find the values of viewstate of previous page( ViewState["yourvalue"] and ViewState["yourcity"])

let us do it at page load of Default.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null && PreviousPageViewState != null)
        {
            var sg = PreviousPageViewState["yourvalue"].ToString();
            var nev = PreviousPageViewState["yourcity"].ToString();
        }
    }

So we are done. you can access the viewstate value of previous page.

Get value of BoundField column set to Visible=False in GridView

 When you set Visible property to False for a BoundField column then it is not possible to get value of such column and hence you need to make use of DataKeyNames (DataKeys) property of ASP.Net GridView.

What are DataKeyNames and DataKeys?
      DataKeyNames is the property of GridView which allows us to set the names of the Column Fields that we want to use in code but do not want to display it. Example Primary Keys, ID fields, etc.
The values Column Fields which are set in DataKeyNames are available in code in DataKeys object which saves it in an Array called as DataKeyArray.

 Using DataKeyNames and DataKeys in GridView
   Using DataKeyNames and DataKeys is fairly simple, you just need to set the name of the Column in DataKeyNames property as shown below. Here CustomerId is the name of the Column.
DataKeyNames="CustomerId"

And then in code access it using the RowIndex of the GridView Row to get the value of the Column for that particular Row.
int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Values[0]);







 Getting the DataKeys value for a particular GridView Row
Inside the Button click event handler, first the GridView Row is determined using the NamingContainer property and then finally the Row Index is determined.
Using the Row Index, the DataKeys array is accessed and the value of the Column is fetched.
C#
protected void GridView_Button_Click(object sender, EventArgs e)
{
    //Determine the RowIndex of the Row whose Button was clicked.
    int rowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;

    //Get the value of column from the DataKeys using the RowIndex.
    int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Values[0]);
}

VB.Net
Protected Sub GridView_Button_Click(sender As Object, e As EventArgs)
    'Determine the RowIndex of the Row whose Button was clicked.
    Dim rowIndex As Integer = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow).RowIndex

    'Get the value of column from the DataKeys using the RowIndex.
    Dim id As Integer = Convert.ToInt32(GridView1.DataKeys(rowIndex).Values(0))
End Sub

Tuesday 2 June 2015

What is d difference between overriding and overloading ?

Overloading

a)In this approach we can define multiple   methods with same name changing their signature means different parameters

b) This can be performed within class as well as  within child class

c) Doesn't require any permission from parent  for overloading its method in child

Overriding

 a.It is an approach of defining multiple methods with same name and same signature

b. this can be performed only under child class

c. Requires an explicit permission from parent  to override its methods in child

Tuesday 17 March 2015

Extract Files from Folder and Bind with Asp.Net GridView – C#

Access to files and folders in a remote server can be limited, but .Net has provided us with a variety of classes in its “System.IO” namespace, exclusively for safely manipulating and viewing files like ‘Word’, ‘Excel’, ‘PDF’, ‘JPG’ etc. Once files are extracted from the folder, we can bind all the files to an Asp.Net GridView control to allow users to view it on a web page.


ASPX Code:
<!DOCTYPE html>

<html>
<head>
    <title>Display | Bind Files from Folder to GridView</title>

    <style type="text/css">
        div
        {
            font:11px Verdana;
            width:750px;
        }

        .grid
        {
            width:100%;
            font:inherit;
            background-color:#FFF;
            border:solid 1px #525252;
        }
       
        .grid td
        {
            font:inherit;
            padding:2px;
            border:solid 1px #C1C1C1;
            color:#333;
            text-align:center;
            text-transform:uppercase;
        }
       
        .grid th {
            padding:3px;
            color:#FFF;
            background:#424242 url(grd.png) repeat-x top;
            border-left:solid 1px #525252;
            font:inherit;
            text-align:center;
            text-transform:uppercase;
        }
       
        #drop1
        {
            width:70px;
            padding:3px;
        }

    </style>
</head>

<body>
    <form id="form1" runat="server">

    <div>

        <%--LISTBOX SHOWING A LIST OF FILE TYPES.--%>
       
        <p>
            <asp:ListBox id="drop1" rows="3" runat="server">
                    <asp:ListItem selected="true">All</asp:ListItem>
                    <asp:ListItem>pdf</asp:ListItem>
                    <asp:ListItem>jpg</asp:ListItem>
                    <asp:ListItem>png</asp:ListItem>
                    <asp:ListItem>txt</asp:ListItem>
                    <asp:ListItem>doclt/asp:ListItem>
                </asp:ListBox>

                <input type="button" id="btShowFiles" onserverclick="btShowFiles_Click"
                    value="Show Files" runat="server" />
        </p>
      
        <%--ADD A GRIDVIEW WITH FEW COLUMNS--%>
        <asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true"
            AllowPaging="true" PageSize="5" AutoGenerateColumns="false"
            OnPageIndexChanging="GridView1_PageIndexChanging" runat="server">
               
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate><asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="File Length">
                    <ItemTemplate><asp:Label ID="lblLen" runat="server" Text='<%#Eval("Length")%>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="File Extention">
                    <ItemTemplate><asp:Label ID="lblFileType" runat="server" Text='<%#Eval("Extension")%>'>
                        </asp:Label></ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Creation Date & Time">
                    <ItemTemplate><asp:Label ID="lblDateTime" runat="server" Text='<%#Eval("CreationTime")%>'>
                        </asp:Label></ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
       
        <%--A LABEL SHOWING NUMBER OF FILES FOUND IN THE FOLDER.--%>
        <p><asp:Label Text="" ID="lblMsg" runat="server"></asp:Label></p>

    </div>
    </form>

</body>
</html>

C# Code:
using System;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void btShowFiles_Click(object sender, EventArgs e)
    {
        ViewState["FileType"] = drop1.SelectedValue;     // GET THE FILE TYPE.
        GetFilesFromFolder();
    }

    // GRIDVIEW PAGING.
    protected void GridView1_PageIndexChanging(object sender,
        System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GetFilesFromFolder();
    }

    private void GetFilesFromFolder()
    {
        // GET A LIST OF FILES FROM A SPECIFILED FOLDER.
        DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("my_demo_folder\\"));   
       
        FileInfo[] listfiles = objDir.GetFiles("*." + ((string)ViewState["FileType"] != "All" ?
            ViewState["FileType"] : "*"));

        if (listfiles.Length > 0)
        {
            // BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
            GridView1.Visible = true;
            GridView1.DataSource = listfiles;
            GridView1.DataBind();

            lblMsg.Text = listfiles.Length + " files found";   
        }
        else {
            GridView1.Visible = false ;
            lblMsg.Text = "No files found";
        }
    }
}

Friday 13 March 2015

Subtotal row in Gridview

 Sql:


select  distinct stor_id,ord_num,title_id,qty from sales
group by stor_id,ord_num,title_id,qty
  
From the result of the above sql, the program find the subtotal of each store and display in 
the GridView. After calculating the subtotal, we are forced to insert a new row after each 
store data and display the subtotal.

Default.aspx
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
 onrowdatabound="GridView1_RowDataBound"  onrowcreated="GridView1_RowCreated">
 <Columns>
    <asp:BoundField DataField="stor_id" HeaderText="stor_id" />
    <asp:BoundField DataField="ord_num" HeaderText="ord_num" />
    <asp:BoundField DataField="title_id" HeaderText="title_id" />
    <asp:BoundField DataField="qty" HeaderText="qty" ItemStyle-HorizontalAlign="Right"/>
 </Columns>
 </asp:GridView>
 </div>
 </form>
</body>
</html>
 
 
C# Source Code
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
 int qtyTotal = 0;
 int storid = 0;
 int rowIndex = 1;
 protected void Page_Load(object sender, EventArgs e)
 {
  SqlDataAdapter adapter = new SqlDataAdapter();
  DataSet ds = new DataSet();
  int i = 0;
  string sql = null;
  string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
  sql = "select  distinct top 14 stor_id,ord_num,title_id,qty from sales group by stor_id,ord_num,title_id,qty";
  SqlConnection connection = new SqlConnection(connetionString);
  connection.Open();
  SqlCommand command = new SqlCommand(sql, connection);
  adapter.SelectCommand = command;
  adapter.Fill(ds);
  adapter.Dispose();
  command.Dispose();
  connection.Close();
  GridView1.DataSource = ds.Tables[0];
  GridView1.DataBind();
 }
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   storid = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString());
   int tmpTotal = Convert.ToInt32 (DataBinder.Eval(e.Row.DataItem, "qty").ToString());
   qtyTotal += tmpTotal;
  }
 }
 protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
 {
  bool newRow = false;
  if ((storid > 0) && (DataBinder.Eval(e.Row.DataItem, "stor_id") != null))
  {
   if (storid != Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString()))
    newRow = true;
  }
  if ((storid > 0) && (DataBinder.Eval(e.Row.DataItem, "stor_id") == null))
  {
   newRow = true;
   rowIndex = 0;
  }
  if (newRow)
  {
   GridView GridView1 = (GridView)sender;
   GridViewRow NewTotalRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
   NewTotalRow.Font.Bold = true;
   NewTotalRow.BackColor = System.Drawing.Color.Gray;
   NewTotalRow.ForeColor = System.Drawing.Color.White;
   TableCell HeaderCell = new TableCell();
   HeaderCell.Text = "Sub Total";
   HeaderCell.HorizontalAlign = HorizontalAlign.Left  ;
   HeaderCell.ColumnSpan = 3;
   NewTotalRow.Cells.Add(HeaderCell);
   HeaderCell = new TableCell();
   HeaderCell.HorizontalAlign = HorizontalAlign.Right;
   HeaderCell.Text = qtyTotal.ToString();
   NewTotalRow.Cells.Add(HeaderCell);
   GridView1.Controls[0].Controls.AddAt(e.Row.RowIndex + rowIndex, NewTotalRow);
   rowIndex++;
   qtyTotal = 0;
  }
 }
}
 
VB.Net Source Code
 
Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    Dim qtyTotal As Integer = 0
    Dim storid As Integer = 0
    Dim rowIndex As Integer = 1
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim adapter As New SqlDataAdapter()
        Dim ds As New DataSet()
        Dim i As Integer = 0
        Dim sql As String = Nothing
        Dim connetionString As String = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****"
        sql = "select  distinct top 14 stor_id,ord_num,title_id,qty from sales group by stor_id,ord_num,title_id,qty"
        Dim connection As New SqlConnection(connetionString)
        connection.Open()
        Dim command As New SqlCommand(sql, connection)
        adapter.SelectCommand = command
        adapter.Fill(ds)
        adapter.Dispose()
        command.Dispose()
        connection.Close()
        GridView1.DataSource = ds.Tables(0)
        GridView1.DataBind()
    End Sub
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            storid = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString())
            Dim tmpTotal As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "qty").ToString())
            qtyTotal += tmpTotal
        End If
    End Sub
    Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        Dim newRow As Boolean = False
        If (storid > 0) AndAlso (DataBinder.Eval(e.Row.DataItem, "stor_id") IsNot Nothing) Then
            If storid <> Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "stor_id").ToString()) Then
                newRow = True
            End If
        End If
        If (storid > 0) AndAlso (DataBinder.Eval(e.Row.DataItem, "stor_id") Is Nothing) Then
            newRow = True
            rowIndex = 0
        End If
        If newRow Then
            Dim GridView1 As GridView = DirectCast(sender, GridView)
            Dim NewTotalRow As New GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert)
            NewTotalRow.Font.Bold = True
            NewTotalRow.BackColor = System.Drawing.Color.Gray
            NewTotalRow.ForeColor = System.Drawing.Color.White
            Dim HeaderCell As New TableCell()
            HeaderCell.Text = "Sub Total"
            HeaderCell.HorizontalAlign = HorizontalAlign.Left
            HeaderCell.ColumnSpan = 3
            NewTotalRow.Cells.Add(HeaderCell)
            HeaderCell = New TableCell()
            HeaderCell.HorizontalAlign = HorizontalAlign.Right
            HeaderCell.Text = qtyTotal.ToString()
            NewTotalRow.Cells.Add(HeaderCell)
            GridView1.Controls(0).Controls.AddAt(e.Row.RowIndex + rowIndex, NewTotalRow)
            rowIndex += 1
            qtyTotal = 0
        End If
    End Sub
End Class 
 

Thursday 19 February 2015

SQL Bulk copy from DataTable in ASP.NET, C#

SQL Bulk copy from DataTable in ASP.NET, C#:

Create Table "EmployeeInfo":

Name NVarChar(255) not null
Adderss NVarChar(255) not null
Phone NVarChar(12) not null

Create Store Procedure "InsertData_Employee_SP":

CREATE PROCEDURE InsertData_Employee_SP
(
     @xmlString VARCHAR(MAX)
)
AS
BEGIN

      DECLARE @xmlHandle INT
      DECLARE @stagingTable TABLE
      (
         [Name]               VARCHAR(50),
         [Address]            VARCHAR(50),
         [Phone]              VARCHAR(50)
      )
             
      EXEC sp_xml_preparedocument @xmlHandle output, @xmlString

      INSERT INTO @stagingTable
      SELECT  [Name],
                  [Address],
                  [Phone]   
      FROM  OPENXML (@xmlHandle, '/DataTable',1)
                        WITH (
                               [Name]  varchar(50)   '@Name',
                                [Address]   varchar(50)   '@Address',
                                [Phone]      varchar(50)    '@Phone'
                               )

      INSERT INTO EmployeeInfo([Name], [Address], [Phone])
            (SELECT [Name] , [Address],[Phone]FROM @stagingTable)
    
      EXEC sp_xml_removedocument @xmlHandle
END

Code in C#:
Sample Data  Table 

DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Phone");
dt.Rows.Add("Sujoy Santra", "Kolkata", "123456890");
dt.Rows.Add("Sanjoy Roy", "Kolkata", "99999900");
dt.Rows.Add("Dilip Pal", "Mumbai", "9876543210");

Convert data table to XML:
 private static string ConvertToXML(DataTable dt)
{
      DataSet dsBuildSQL = new DataSet();
      StringBuilder sbSQL;
      StringWriter swSQL;
      string XMLformat;
      try
      {
           sbSQL = new StringBuilder();
           swSQL = new StringWriter(sbSQL);
           dsBuildSQL.Merge(dt, true, MissingSchemaAction.AddWithKey);
           dsBuildSQL.Tables[0].TableName = "DataTable";
           foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
           {
               col.ColumnMapping = MappingType.Attribute;
           }
           dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
           XMLformat = sbSQL.ToString();
           return XMLformat;
       }
       catch (Exception sysException)
       {
           throw sysException;
       }
}

Now Insert the data table to database:

SqlConnection conn = newSqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ToString());
SqlCommand command = new SqlCommand("InsertData_Employee_SP  '" + xmlData + "'", conn);
conn.Open();
command.ExecuteNonQuery();
conn.Close();

Bind Dropdownlist in Gridview in Asp.net

Bind Dropdownlist in Gridview in Asp.net:

Code in ASPX
 <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Bind Dropdownlist  inside gridview</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" OnRowDataBound="gv_RowDataBound" >
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="CountryId" HeaderText="CountryId" />
<asp:BoundField DataField="CountryName" HeaderText="CountryName" />
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" Width="100px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


Code in C#:
 SqlConnection con =new SqlConnection("Data Source=Your Data Source ;Integrated Security=true;Initial Catalog=SampleDB");

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select  CountryId,CountryName from CountryMaster", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gv.DataSource = ds;
gv.DataBind();

}

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("ddlCity");
int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select * from StateMaster where CountryID=" + CountryId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "StateName";
ddl.DataValueField = "StateID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select State--", "0"));
}
}

Friday 9 January 2015

Gridview To Pdf in C# & VB.NET

Gridview To Pdf in C# & VB.NET:
 C#

private void PDF_Export()

{

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition",

        "attachment;filename=GridViewExport.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    htmlparser.Parse(sr);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();

}



VB.Net

Private Sub PDF_Export()

  Response.ContentType = "application/pdf"

  Response.AddHeader("content-disposition", _

   "attachment;filename=GridViewExport.pdf")

  Response.Cache.SetCacheability(HttpCacheability.NoCache)

  Dim sw As New StringWriter()

  Dim hw As New HtmlTextWriter(sw)

  GridView1.AllowPaging = False

  GridView1.DataBind()

  GridView1.RenderControl(hw)

  Dim sr As New StringReader(sw.ToString())

  Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)

  Dim htmlparser As New HTMLWorker(pdfDoc)

  PdfWriter.GetInstance(pdfDoc, Response.OutputStream)

  pdfDoc.Open()

  htmlparser.Parse(sr)

  pdfDoc.Close()

  Response.Write(pdfDoc)

  Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

Gridview To Excel In C# & VB.NET

Gridview To Excel In C# & VB.NET:

C#

private void Excel_Export()

{

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

     "attachment;filename=GridViewExport.xls");

    Response.Charset = "";

    Response.ContentType = "application/vnd.ms-excel";

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    for (int i = 0; i < GridView1.Rows.Count; i++)

    {

        GridViewRow row = GridView1.Rows[i];

        //Apply text style to each Row

        row.Attributes.Add("class", "textmode");

    }

    GridView1.RenderControl(hw);



    //style to format numbers to string

    string style = @"<style> .textmode { mso-number-format:\@; } </style>";

    Response.Write(style);

    Response.Output.Write(sw.ToString());

    Response.Flush();

    Response.End();

}

   
                 

VB.Net



Private Sub Excel_Export()

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

    "attachment;filename=GridViewExport.xls")

   Response.Charset = ""

   Response.ContentType = "application/vnd.ms-excel"

   Dim sw As New StringWriter()

   Dim hw As New HtmlTextWriter(sw)

   GridView1.AllowPaging = False

   GridView1.DataBind()

   For i As Integer = 0 To GridView1.Rows.Count - 1

     Dim row As GridViewRow = GridView1.Rows(i)

    'Apply text style to each Row

     row.Attributes.Add("class", "textmode")

   Next

   GridView1.RenderControl(hw)



   'style to format numbers to string

   Dim style As String = "<style> .textmode " _

     & "{ mso-number-format:\@; } </style>"

   Response.Write(style)

   Response.Output.Write(sw.ToString())

   Response.Flush()

   Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

Gridview To Word Export in C# & VB.NET

 Gridview To Word Export in C# & VB.NET:
C#

private void Word_Export()

{

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

      "attachment;filename=GridViewExport.doc");

    Response.Charset = "";

    Response.ContentType = "application/vnd.ms-word ";

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    Response.Output.Write(sw.ToString());

    Response.Flush();

    Response.End();

}



VB.Net

Private Sub Word_Export()

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

    "attachment;filename=GridViewExport.doc")

   Response.Charset = ""

   Response.ContentType = "application/vnd.ms-word "

   Dim sw As New StringWriter()

   Dim hw As New HtmlTextWriter(sw)

   GridView1.AllowPaging = False

   GridView1.DataBind()

   GridView1.RenderControl(hw)

   Response.Output.Write(sw.ToString())

   Response.Flush()

   Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

Wednesday 7 January 2015

Nested GridView in ASP.NET ,C# (GridView Inside a GridView)

Nested GridView in ASP.NET ,C# (GridView Inside a GridView) :

In Master GridView (GV_Master) I’ll show you the Customer’s details i.e.,CustomerId, CustomerName and CustomerAddress from ‘Customer_Details’ table.

Then in the Child GridView(GV_Child) I’ll show you Order details of corresponding to the Customers i.e. CustomerID.

In Master GridView (GV_Master) I’ll show you the Customer’s details i.e., CustomerName and CustomerAddress from ‘Customer_Details’ table. Then in the Child GridView(GV_Child) I’ll show you Order details of corresponding Customers i.e. CustomerIDand.

Creating Master GridView (GV_Master):
<asp:GridView ID="GV_Master" runat="server"
          AutoGenerateColumns="false" DataKeyNames="CustomerId"
          OnRowDataBound="GV_Master_OnRowDataBound" CssClass="Grid">
    <columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerName " HeaderText="Customer Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerAddress " HeaderText="Customer Address " />
    </columns>
  </asp:GridView>

So, now it shows only two column i.e. CustomerName and CustomerAddress . Now, I’ll insert ‘plus sign image’ to the First Column of every row. As because, when I’ll click this ‘plus sign image’ then the Child GridView will displayed and the ‘plus sign image’ will be the ‘minus sign image’. And when I’ll click the ‘minus sign image’ the Child GridView will remove from our sight and ‘minus sign image’ becomes the ‘plus sign image’ like toggle. So, I’ve to take an ItemTemplate within a TemplateField inside the Columns at first position

Please See The Code:
<asp:GridView ID="GV_Master" runat="server" AutoGenerateColumns="false" DataKeyNames="CustomerId"
    OnRowDataBound="GV_Master_OnRowDataBound" CssClass="Grid">
    <columns>
        <asp:TemplateField ItemStyle-Width="20px">
            <itemtemplate>
                <a href="java<!-- no -->script:divexpandcollapse('div<%# Eval(">
                    <img id="imgdiv<%# Eval(" alt="Details" src="images/plus.png" />
                </a>
       
               <asp:BoundField ItemStyle-Width="150px" DataField="CustomerName "    HeaderText="Customer Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerAddress " HeaderText="Customer Address " />
            </itemtemplate>
    </columns>
</asp:GridView>


Now, you see that I’ve linked a JavaScript function to the ‘plus sign image’ which does the all functionality what I’ve told above against the Click event of the ‘plus sign image’. This JavaScript function takes the Div name in which the Child GridView exists. There will be one Child GridView for each row of the Master GridView. So, the Div id must be different. That’s why I concatenate Div id with CustomerId and there will one ‘plus sign image’ for each row of the Master GridView, so I also concatenate the img id with CustomerId. Now lets add the Div just after the link of the ‘plus sign image’ and implement Child GridView under that Div:

<asp:GridView ID="GV_Master" runat="server"
           AutoGenerateColumns="false" DataKeyNames="CustomerId"
    OnRowDataBound="GV_Master_OnRowDataBound" CssClass="Grid">
    <columns>
        <asp:TemplateField ItemStyle-Width="20px">
            <itemtemplate>
                <a href="java<!-- no -->script:divexpandcollapse('div<%# Eval(">
                    <img id="imgdiv<%# Eval(" alt="Details" src="images/plus.png" />
                </a>               
                 <div id='div<%# Eval("CustomerId")%>' style="display: none; left: 5px; overflow: auto;">
                    <asp:GridView ID="GV_Child"
                            runat="server" AutoGenerateColumns="false"
                            DataKeyNames="CustomerId" CssClass="ChildGrid">
                        <columns>
                            <asp:BoundField ItemStyle-Width="150px"
                              DataField="OrderId" HeaderText="Order Id" />
                            <asp:BoundField ItemStyle-Width="150px"
                              DataField="OrderDate" HeaderText="Order Date" />
                        </columns>
                   
                </div>
            </itemtemplate>
       
      <asp:BoundField ItemStyle-Width="150px" DataField="CustomerName "    HeaderText="Customer Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerAddress " HeaderText="Customer Address " />
    </columns>
</asp:GridView>

Lets see the little JQuery which checks whether the ‘plus sign image’ source contains the path of the ‘plus sign’ image or ‘minus sign’ image and do said functionality accordingly:


function divexpandcollapse(divname) {
    var img = "img" + divname;
    if ($("#" + img).attr("src") == "images/plus.png") {
        $("#" + img)
    .closest("tr")
    .after("" + $("#" + divname)
    .html() + "")
        $("#" + img).attr("src", "images/minus.png");
    } else {
        $("#" + img).closest("tr").next().remove();
        $("#" + img).attr("src", "images/plus.png");
    }
}

Now the client side part is over. The main part is how you fill the Child GridView? Don’t worry, there is an event which is triggered when there is one container control within the row of the GridView. The event is OnRowDataBound. And I’ve already added this event to the Master GridView properties and the name of event handler is: GV_Master_OnRowDataBound. And we also fill the Master GridView in the Page_Load() event. So lets implement:

Code Behind(C#):
protected void Page_Load(object sender, EventArgs e)
{
    GV_Master.DataSource =
      SelectData("SELECT  CustomerId, ContactName, CustomerAddress FROM Customers_Details");
    grdViewCustomers.DataBind();
}

private DataTable SelectData(string sqlQuery)
{
    string connectionString =
      System.Web.Configuration.WebConfigurationManager.ConnectionStrings[
      "con"].ConnectionString;
    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, connectionString))
    {
        DataTable dt = new DataTable("Customers_Details");
        sqlDataAdapter.Fill(dt);
        return dt;
    }
}

protected void GV_Master_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string customerId = grdViewCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
        GridView gvChild= (GridView)e.Row.FindControl("GV_Child");
        grdViewOrdersOfCustomer.DataSource = SelectData(
          "SELECT CustomerId, OrderId, OrderDate FROM Orders_Details WHERE CustomerId='" +
          customerId + "'");
        gvChild.DataBind();
    }
}


Tuesday 23 December 2014

What is Lvalues and Rvalues in C#

What is  Lvalues and Rvalues in C#:

There are two kinds of expressions in C#:

    lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

    rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:

int g = 10;

But following is not a valid statement and would generate compile-time error:

10 = 100;

Wednesday 29 October 2014

Master page with Menu Control in Asp.net C# with Example

Master page with Menu Control in Asp.net C# with Example

Here I will explain how to create master page with menu in asp.net example or how to use asp.net menu control in master page to create menu and submenus. Here I will use sitemap and sitemapdatasource control to bind asp.net menu in master page.


Right click on website >> select Add New Item >> Select SiteMap >> Click OK
Once SiteMAP added to website open SiteMAP and write the following code

 <?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="" title=""  description="">
<siteMapNode url="Default.aspx" title="Home"  description="Home Page"/>
<siteMapNode url="Forums.aspx" title="Forums"  description="Forums Page"/>
<siteMapNode url="Careers.aspx" title="Careers"  description="Careers Page" >
<siteMapNode url="Jobs.aspx" title="Jobs"  description="Jobs Page" />
<siteMapNode url="upload.aspx" title="Upload"  description="Upload Page" />
</siteMapNode>
<siteMapNode url="ContactUs.aspx" title="Contact US"  description="ContacUs Page" />
</siteMapNode>
</siteMap>

Same way we can add master page Right click on website >> Select Add New item >> Select Master Page >> Click OK
Now open Masterpage and write the following code
 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Master Page with Menu control in asp.net with example</title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
.parent_menu
{
width: 110px;
background-color: #8AE0F2;
color: #000;
text-align: center;
height: 30px;
margin-right: 5px;
}
.child_menu
{
width: 110px;
background-color: #000;
color: #fff;
text-align: center;
height: 30px;
line-height: 30px;

}
.sub_menu
{
width: 110px;
background-color: #000;
color: #fff;
text-align: center;
height: 30px;
line-height: 30px;
margin-top: 5px;
}
.selected_menu
{
background-color: #FF6600;
}
.hover_menu
{
background-color: #990000;
color:#fff;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Horizontal">
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="parent_menu" />
</LevelMenuItemStyles>
<LevelSelectedStyles>
<asp:MenuItemStyle CssClass="child_menu" />
</LevelSelectedStyles>
<DynamicMenuItemStyle CssClass="sub_menu" />
<DynamicHoverStyle CssClass="hover_menu" />
<StaticSelectedStyle CssClass="selected_menu" />
<StaticHoverStyle CssClass="hover_menu" />
</asp:Menu>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

Now open Default.aspx page and add master page like as shown below 

 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" MasterPageFile="~/MasterPage.master" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>

Asp.net Display List of Files from Server Folder in Gridview

Asp.net Display List of Files from Server Folder in Gridview using C#

To display files from folder in Gridview we need to write the code like as shown below


 first create new web application and write the following code in aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get files from folder & bind to gridview in c#.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGetFiles" Text="Get Files From Folder" runat="server" onclick="btnGetFiles_Click" />
<asp:GridView ID="gvDetails" CellPadding="5" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>

</html>

 
 Once you add namespaces write the following code in code behind
C# Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;

 // insert files in folder
protected void btnGetFiles_Click(object sender, EventArgs e)
{
BindGridview();
}
// Bind Data to Gridview
protected void BindGridview()
{
string[] filesPath = Directory.GetFiles(Server.MapPath("~/SampleFiles/"));
List<ListItem> files = new List<ListItem>();
foreach (string path in filesPath)
{
files.Add(new ListItem(Path.GetFileName(path)));
}
gvDetails.DataSource = files;
gvDetails.DataBind();
}

Get Asp.net Gridview Selected Row Values on Button click in C#

Get Asp.net Gridview Selected Row Values on Button click in C# 

Here I will explain how to add checkboxe in asp.net gridview and get gridview selected rows data on button click in asp.net and get checked rows data on button click and how to work with those checked rows in asp.net using c#.

First create one new web application and open your Default.aspx and write the following code .

 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Checkbox Selected Rows in Asp.net Gridview</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView AutoGenerateColumns="false" ID="gvDetails" CellPadding="5" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkDetails" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserId">
<ItemTemplate>
<asp:Label id="lblUserid" runat="server" Text='<%#Eval("UserId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label id="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Education">
<ItemTemplate>
<asp:Label id="lblEducation" runat="server" Text='<%#Eval("Education") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="btngetdetails" Text="Get Selected Checkboxes" runat="server"
onclick="btngetdetails_Click" />
<br />
<b>Selected Values are:</b><asp:Label ID="lblselected" runat="server" />
</form>
</body>
</html>

 Now in code behind file write the code like as shown below
 using System;
using System.Data;
using System.Web.UI.WebControls;
public partial class BindGridviewwithCheckboxes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Rows.Add(1, "Sumit Kemar Sen", "B.Tech");
        dt.Rows.Add(2, "Soumi Santra", "MA");
        dt.Rows.Add(3, "Sujoy Santra", "MCA");
        dt.Rows.Add(4, "Pradipta Chowdhury", "MCA");
        dt.Rows.Add(6, "Sourav Mukherjee", "B.Tech");
        dt.Rows.Add(7, "Sandipan Maji", "B.Tech");
        dt.Rows.Add(8, "Mithun Patra", "MCA");
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
}
protected void btngetdetails_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string str = "";
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("UserId"), new DataColumn("Status") });
foreach (GridViewRow row in gvDetails.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox bf = (row.Cells[3].FindControl("chkDetails") as CheckBox);
string id = (row.Cells[0].FindControl("lblUserid") as Label).Text;
if (bf.Checked)
{
str = str+ id + ",";
}
}
}
str = str.Remove(str.Length - 1, 1);
lblselected.Text = str;
}
}

Friday 12 September 2014

What is the difference between .EXE and .DLL files?

 What is the difference between .EXE and .DLL files?
EXE

  1. It is an executable file, which can be run independently.
  2. EXE is an out-process component, which means that it runs in a separate process.
  3. It cannot be reused in an application.
  4. It has a main function.

DLL
  1. It is Dynamic Link Library that is used as a part of EXE or other DLLs. It cannot be run independently.
  2. It runs in the application process memory, so it is called as in-process component.
  3. It can be reused in an application.
  4. It does not have a main function.

Wednesday 27 August 2014

Upload XML into SQL Server

Pass XML parameter to Stored Procedure in C#
In this article I  will explain how to insert data XML to SQL server.
In previous article I explain how pass XML as a parameter in stored procedure.

Now We will see how it works in ASP.NET, C#,

Sample XML:
<?xmlversion="1.0"standalone="yes"?>
<Customers>
 <CustomerId ="1">
    <Name>Sujoy Santra</Name>
    <Country>Indias</Country>
 </Customer>
 <CustomerId = "2">
    <Name>Mithun Patra</Name>
    <Country>India</Country>
 </Customer>
    <CustomerId ="3">
    <Name>Pradipta Chowdhury</Name>
    <Country>India</Country>
 </Customer>
    <CustomerId ="4">
    <Name>Sumit Kumar Sen</Name>
    <Country>India</Country>
 </Customer>
</Customers>

Take one fileuploader control and one button in ASPX page.

<asp:FileUpload ID = "FileUpload1" runat = "server" />
<asp:Button ID="Button1" Text="Upload XML" runat="server" OnClick="UploadXML" />


Write the following code in C# page:

protected void UploadXML(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string filePath = Server.MapPath("~/Uploads/") + fileName;
    FileUpload1.SaveAs(filePath);
    string xml = File.ReadAllText(filePath);
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("InsertXML"))
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@xml", xml);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

Run the code.