C#

Friday, February 21, 2014

How to Upload CSV File Data into Database Table (Employee) and Display Data in Asp.net Grid view

In Previous tutorial
Export Asp.net Grid view Data In to CSV File: Using Asp.net, C#, Entity Data Model
For That  I Create a Employee table and Added That Table to Ado.Net EntityDataModel
Now, I will Explain

How to Upload CSV File Data into Database Table (Employee) and Display Data in Asp.net Grid view

Step:1 

Add Web form in visual studio project name as Test.aspx:      
<div>
            <table>
                <tr>
                    <td>
                        Select File :
                    </td>
                    <td>
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    </td>
                    <td>
                        <asp:Button ID="btnImportFromCSV" runat="server" Text="Import Data to Database" OnClick="btnImportFromCSV_Click" />
                    </td>
                </tr>
            </table>
            <div>
                <br />
                <asp:Label ID="lblMessage" runat="server" Font-Bold="true" />
                <br />
                <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
                    <EmptyDataTemplate>
                        <div style="padding: 10px;">
                            No Data Found!</div>
                    </EmptyDataTemplate>
                    <Columns>
                        <asp:BoundField HeaderText="Id" DataField="Id" />
                        <asp:BoundField HeaderText="EmployeeName" DataField="EmployeeName" />
                        <asp:BoundField HeaderText="Salary" DataField="Salary" />                      
                    </Columns>
                </asp:GridView>
                <br />
               
            </div>
        </div>

Step:2

Note:
Add UploadDocuments folder to solution

Step:3

In Code Behind Write Following Code:
Test.aspx.cs:
In Page Load:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateData();
                lblMessage.Text = "Current Database Data.";
            }
        }
Implement a Method populateData():

        private void populateData()
        {
            using (TestEntities dc = new TestEntities())
            {
                gvData.DataSource = dc.Employees.ToList();
                gvData.DataBind();
            }
        }

 Step:4


Write Code For ImportData to data base Button Click Event:
        protected void btnImportFromCSV_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile.ContentType == "text/csv" || FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel")
            {
                string fileName = Path.Combine(Server.MapPath("~/UploadDocuments"), Guid.NewGuid().ToString() + ".csv");
                try
                {
                    FileUpload1.PostedFile.SaveAs(fileName);

                    string[] Lines = File.ReadAllLines(fileName);
                    string[] Fields;

                    //Remove Header line
                    Lines = Lines.Skip(1).ToArray();
                    List<Employee> emList = new List<Employee>();
                    foreach (var line in Lines)
                    {
                        Fields = line.Split(new char[] { ',' });
                        emList.Add(
                            new Employee
                            {
                                Id = Convert.ToInt32(Fields[0].Replace("\"", "")), // removed ""
                                EmployeeName = Fields[1].Replace("\"", ""),
                                Salary = Convert.ToDecimal(Fields[2].Replace("\"", "")),                              
                            });
                    }

                    // Update database data
                    using (TestEntities dc = new TestEntities())
                    {
                        foreach (var i in emList)
                        {
                            var v = dc.Employees.Where(a => a.Id.Equals(i.Id)).FirstOrDefault();
                            if (v != null)
                            {
                                v.Id = i.Id;
                                v.EmployeeName = i.EmployeeName;
                                v.Salary = i.Salary;
                            }
                            else
                            {
                                dc.Employees.AddObject(i);
                            }
                        }

                        dc.SaveChanges();

                        // populate updated data
                        populateDatabaseData();
                        lblMessage.Text = "Successfully Done. Now upto data is following.....";
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

 Note: This Code Tested Several Time Working Perfect Go throw Above Code.If Any Queries Post Below


Export Asp.net Grid view Data In to CSV File: Using Asp.net, C#, Entity Data Model

Step 1:

Create a data Base Table in SQL Server 2008:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [EmployeeName] [nvarchar](30) NULL,
      [Salary] [decimal](7, 2) NULL,
PRIMARY KEY CLUSTERED
(
      [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 2:

In Visual Studio Create a Project Some Name(Ex:TestProject)
In Visual Studio Add New Ado.net Entity data Model Give the Wizard data and Add Employee Table to Model

Step 3:

In Visual Studio Add Web Form Name Some Test.aspx
Write code in Test.aspx:
<div>
                <br />
                <asp:Label ID="lblMessage" runat="server" Font-Bold="true" />
                <br />
                <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
                    <EmptyDataTemplate>
                        <div style="padding: 10px;">
                            No Data Found!</div>
                    </EmptyDataTemplate>
                    <Columns>
                        <asp:BoundField HeaderText="Id" DataField="Id" />
                        <asp:BoundField HeaderText="EmployeeName" DataField="EmployeeName" />
                        <asp:BoundField HeaderText="Salary" DataField="Salary" />                      
                    </Columns>
                </asp:GridView>
                <br />
                <asp:Button ID="btnExportToCSV" runat="server" Text="Export Data to CSV" OnClick="btnExportToCSV_Click" />
            </div>

Step 4:

In Code Behind Means Test.aspx.cs:
Page Load:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateData();
                lblMessage.Text = "Current Database Data.";
            }
        }
Implement Code For populateData()

private void populateData()
        {
            using (TestEntities dc = new TestEntities())
            {
                gvData.DataSource = dc.Employees.ToList();
                gvData.DataBind();
            }
        }
Write Code For ExportToCsv Button Click Event:
        protected void btnExportToCSV_Click(object sender, EventArgs e)
        {
            List<Employee> emList = new List<Employee>();
            using (TestEntities dc = new TestEntities())
            {
                emList = dc.Employees.ToList();
            }

            if (emList.Count > 0)
            {
                string header = @"""Id"",""EmployeeName"",""Salary""";
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(header);

                foreach (var i in emList)
                {
                    sb.AppendLine(string.Join(",",
                        string.Format(@"""{0}""", i.Id),
                        string.Format(@"""{0}""", i.EmployeeName),
                        string.Format(@"""{0}""", i.Salary)));                     
                }

                // Download Here

                HttpContext context = HttpContext.Current;
                context.Response.Write(sb.ToString());
                context.Response.ContentType = "text/csv";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=EmployeeData.csv");
                context.Response.End();
            }          
        }

 Note:I tested Several Times Working Perfect If Any Queries Post Below.Thankyou..

Monday, February 10, 2014

Change Browse/Choose Text in Asp.Net FileUpload Control Awesome Tutorial Using CSS

Introduction:


While File Upload Control In Asp.net All Developers/Designers Suffering From To Change The Text Of Browse/Choose.In this Tutorial I will Resolve That Problem This is Tested Code Working Perfect.


In chrome/Mozilla Firefox


In Internet Explorer


I change Browse/Choose To Some Text . In My Tutorial I replaced With Upload Using Css :



Steps:


In .aspx Page Copy Paste This Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    /* File Upload Design  */
  .file-upload
   {
      display : inline-block;
 overflow: hidden;
 position: relative;
 text-align: center;
 vertical-align: middle;
/* Cosmetics */
 border: 1px solid #5C005C;
 background: #5C005C;
 color: #fff;
/* browser can do it */
 border-radius: 6px;
-moz-border-radius: 6px;
 text-shadow: #000 1px 1px 2px;
-webkit-border-radius: 6px;
    }
   
    /* The button size */
  .file-upload { height: 1.3em; }
  .file-upload,.file-upload span { width: 3.5em; }
   
  .file-upload input
   {
position: absolute;
top: 0;
left: 0;
margin: 0;
font-size: 11px;
/* Loses tab index in webkit if width is set to 0 */
opacity: 0;
filter: alpha(opacity=0);
  }

  .file-upload strong { font: normal 12px Tahoma,sans-serif;text-align:center;vertical-align:middle; }


  .file-upload span
   {
position: absolute;
top: 0; left: 0;
display: inline-block;
/* Adjust button text vertical alignment */
padding-top: .15em;
   }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <label class="file-upload">
            <span><strong>Upload</strong></span>
            <asp:FileUpload ID="FileUpload1" runat="server" Width="60px">
            </asp:FileUpload>
        </label>
    </div>
    </form>
</body>
</html>


OutPut:














Monday, February 3, 2014

RadioButton List control in asp.net using c#

Introduction

The RadioButtonList control provides page developers with a single-selection radio button group that can be dynamically generated through data binding. It contains anItems collection with members that correspond to individual items on the list. To determine which item is selected, test the SelectedItem property of the list.

Specifying List Layout


You can specify how the list is rendered by setting the RepeatLayout and RepeatDirection properties. For information about layout options, see the RepeatLayoutenumeration.
By default, RepeatDirection is set to RepeatDirection.Vertical. Setting this property to RepeatDirection.Horizontal causes the control to render the list horizontally. SomeRepeatLayout settings do not allow horizontal layout. For more information, see the RepeatLayout enumeration.
This control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. You can use validation controls to verify user input before displaying the input text in a RadioButtonListcontrol. ASP.NET provides an input request validation feature to block script and HTML in user input.

Example:

The following code example demonstrates how to programmatically modify the display of a RadioButtonList control.
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head>
    <title>RadioButtonList Example</title>
<script language="C#" runat="server">

        void Button1_Click(object Source, EventArgs e) 
        {
           if (RadioButtonList1.SelectedIndex > -1) 
           {  
              Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
           }
        }

        void chkLayout_CheckedChanged(Object sender, EventArgs e) 
        {

           if (chkLayout.Checked == true) 
           {
              RadioButtonList1.RepeatLayout = RepeatLayout.Table;
           }
           else 
           {
              RadioButtonList1.RepeatLayout = RepeatLayout.Flow;
           }     
        }

        void chkDirection_CheckedChanged(Object sender, EventArgs e) 
        {

           if (chkDirection.Checked == true) 
           {
              RadioButtonList1.RepeatDirection = RepeatDirection.Horizontal;
           }
           else 
           {
              RadioButtonList1.RepeatDirection = RepeatDirection.Vertical;
           }  
        }

     </script>

 </head>
 <body>

     <h3>RadioButtonList Example</h3>

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

         <asp:RadioButtonList id="RadioButtonList1" runat="server">
            <asp:ListItem>Item 1</asp:ListItem>
            <asp:ListItem>Item 2</asp:ListItem>
            <asp:ListItem>Item 3</asp:ListItem>
            <asp:ListItem>Item 4</asp:ListItem>
            <asp:ListItem>Item 5</asp:ListItem>
            <asp:ListItem>Item 6</asp:ListItem>
         </asp:RadioButtonList>

         <br />

         <asp:CheckBox id="chkLayout" OnCheckedChanged="chkLayout_CheckedChanged" Text="Display Table Layout" Checked="true" AutoPostBack="true" runat="server" />

         <br />

         <asp:CheckBox id="chkDirection" OnCheckedChanged="chkDirection_CheckedChanged" Text="Display Horizontally" AutoPostBack="true" runat="server" />

         <br />

         <asp:Button id="Button1" Text="Submit" onclick="Button1_Click" runat="server"/>

         <br />

         <asp:Label id="Label1" font-names="Verdana" font-size="8pt" runat="server"/>

     </form>

 </body>
 </html>
   

RadioButtonList Example

      You selected: Item 3

RadioButton control in asp.net using c#

Introduction

The RadioButton server control permits you to intersperse the radio buttons in a group with other content in the page. The buttons are grouped logically if they all share the same GroupName property.
You can use the RadioButton control to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. ASP.NET provides an input request validation feature to block script and HTML in user input. Validation server controls are also provided to assess user input.

Example:

<%@ Page Language="C#" AutoEventWireup="True" %>
<!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>
    <title>RadioButton Example</title>
<script language="C#" runat="server">

         void SubmitBtn_Click(Object Sender, EventArgs e) {

             if (Radio1.Checked) {
                 Label1.Text = "You selected " + Radio1.Text;
             }
             else if (Radio2.Checked) {
                 Label1.Text = "You selected " + Radio2.Text;
             }
             else if (Radio3.Checked) {
                 Label1.Text = "You selected " + Radio3.Text;
             }
         }

     </script>

 </head>
 <body>

     <h3>RadioButton Example</h3>

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

         <h4>Select the type of installation you want to perform:</h4>

         <asp:RadioButton id="Radio1" Text="Typical" Checked="True" GroupName="RadioGroup1" runat="server" /><br />

         This option installs the features most typically used.  <i>Requires 1.2 MB disk space.</i><br />

         <asp:RadioButton id="Radio2" Text="Compact" GroupName="RadioGroup1" runat="server"/><br />

         This option installs the minimum files required to run the product.  <i>Requires 350 KB disk space.</i><br />

         <asp:RadioButton id="Radio3" runat="server" Text="Full" GroupName="RadioGroup1" /><br />

         This option installs all features for the product.  <i>Requires 4.3 MB disk space.</i><br />

         <asp:button text="Submit" OnClick="SubmitBtn_Click" runat="server"/>

         <asp:Label id="Label1" font-bold="true" runat="server" />

     </form>

 </body>
 </html>

ViewDemo:

Placeholder control in asp.net using c#

Introduction

Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls collection to add, insert, or remove a control in thePlaceHolder control.

Declarative Syntax:

<asp:PlaceHolder
    EnableTheming="True|False"
    EnableViewState="True|False"
    ID="string"
    OnDataBinding="DataBinding event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnUnload="Unload event handler"
    runat="server"
    SkinID="string"
    Visible="True|False"
/>

Example:

<%@ Page Language="C#" AutoEventWireup="True" %>

<!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>
    <title>PlaceHolder Example</title>
<script runat="server">

      void Page_Load(Object sender, EventArgs e)
      {
         HtmlButton myButton = new HtmlButton();

         myButton.InnerText = "Button 1";
         PlaceHolder1.Controls.Add(myButton);

         myButton = new HtmlButton();
         myButton.InnerText = "Button 2";
         PlaceHolder1.Controls.Add(myButton);

         myButton = new HtmlButton();
         myButton.InnerText = "Button 3";
         PlaceHolder1.Controls.Add(myButton);

         myButton = new HtmlButton();
         myButton.InnerText = "Button 4";
         PlaceHolder1.Controls.Add(myButton);
      }

   </script>

</head>

<body>
   <form id="form1" runat="server">
      <h3>PlaceHolder Example</h3>

      <asp:PlaceHolder id="PlaceHolder1" 
           runat="server"/>
   </form>
</body>
</html>

ViewDemo: