Friday, February 27, 2015

Server Side Validation of CheckboxList in ASP.NET & C#

We can Validate CheckboxList using the CustomValidator on Client side and server-side as well.

Our approach here will be validating the checkboxlist on server-side.

1. Add the CheckboxList with some items as below.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
          <asp:ListItem>A</asp:ListItem>
          <asp:ListItem>B</asp:ListItem>
          <asp:ListItem>C</asp:ListItem>
 </asp:CheckBoxList>

2. Add a CustomValidator Control from the toolbox.

I have added a OnServerValidate event which will validate the checkboxlist on server side on button click.


            <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alteast one option"  OnServerValidate="CustomValidator1_ServerValidate" ></asp:CustomValidator>


3. Add a Button to Check the Validations are working.

 <asp:Button ID="Button1" runat="server" Text="Button" />

4. the c# code for validating the list.

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            int count = 0;
            foreach (ListItem item in CheckBoxList1.Items)
            {
                if (item.Selected)
                {
                    count++;
                    break;
                }
            }

            if (count > 0)
                args.IsValid = true;
            else
                args.IsValid = false;

        }

Validate CheckboxList in ASP.NET on Client Side using Javascript

We can Validate CheckboxList using the CustomValidator on Client side and server-side as well.

Our approach here will be validating the checkboxlist on client-side.

1. Add the CheckboxList with some items as below.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
          <asp:ListItem>A</asp:ListItem>
          <asp:ListItem>B</asp:ListItem>
          <asp:ListItem>C</asp:ListItem>
 </asp:CheckBoxList>

2. Add a CustomValidator Control from the toolbox.

I have added a ClientValidateFunction which will be a javascript function ValidateCheckBoxList  to validate.

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alt-east one option" ClientValidationFunction="ValidateCheckBoxList"></asp:CustomValidator>

3. Add a Button to Check the Validations are working.


 <asp:Button ID="Button1" runat="server" Text="Button" />


4. Add the following java script to the Page which will validate the CheckBoxList.

  <script type="text/javascript">
        function ValidateCheckBoxList(source, args) {
            var chkListModules = document.getElementById('<%= CheckBoxList1.ClientID %>');
            var chkListinputs = chkListModules.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }


    </script>

GridView Export To Word ASP.NET & C#

In this article we will see how to export grid-view to excel or word.

Step 1 : Create a new database in SQL server or if you have a database already go to step 2.

CREATE DATABASE (YOUR DATABASE NAME);

Step 2 : Create a table in the database.

CREATE TABLE Employee
(
    EmployeeID INT,
    Name Varchar(250),
    Salary Decimal (10,2)

);

Step 3 : Insert some sample data to the table.

INSERT INTO Employee VALUES (1,'Scott',1000);
INSERT INTO Employee VALUES (2,'John',1100);
INSERT INTO Employee VALUES (3,'Phil',1200);
INSERT INTO Employee VALUES (4,'Peter',1300);
INSERT INTO Employee VALUES (5,'Jose',1400);

INSERT INTO Employee VALUES (6,'Morgan',1500);


Step 4 : Now Add a WebForm to your Project and add the GridView Control and Button to Export the Data.


 <asp:GridView ID="GridView1" runat="server"></asp:GridView>
 <asp:Button ID="btnExportWord" runat="server" Text="Export To Word" OnClick="btnExportWord_Click" />

Step 5 : Add the following code to your Page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
            string connectionString = "Data Source=.SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM Employee";
                cmd.Connection = con;
                con.Open();

                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        private void ExportGridView(string fileName, string contentType)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            Response.Charset = "";
            Response.ContentType = contentType;

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Close();
            Response.End();
        }

    protected void btnExportWord_Click(object sender, EventArgs e)
    {
            ExportGridView("GridData.doc", "application/vnd.ms-word");
     }

        public override void VerifyRenderingInServerForm(Control control)
        {
            
        }

GridView Export To Excel in ASP.NET & C#

In this article we will see how to export grid-view to excel or word.

Step 1 : Create a new database in SQL server or if you have a database already go to step 2.

CREATE DATABASE (YOUR DATABASE NAME);

Step 2 : Create a table in the database.

CREATE TABLE Employee
(
    EmployeeID INT,
    Name Varchar(250),
    Salary Decimal (10,2)

);

Step 3 : Insert some sample data to the table.

INSERT INTO Employee VALUES (1,'Scott',1000);
INSERT INTO Employee VALUES (2,'John',1100);
INSERT INTO Employee VALUES (3,'Phil',1200);
INSERT INTO Employee VALUES (4,'Peter',1300);
INSERT INTO Employee VALUES (5,'Jose',1400);

INSERT INTO Employee VALUES (6,'Morgan',1500);


Step 4 : Now Add a WebForm to your Project and add the GridView Control and Button to Export the Data.

 <asp:GridView ID="GridView1" runat="server"></asp:GridView>
  <asp:Button ID="btnExportExcel" runat="server" Text="Export To Excel" OnClick="btnExportExcel_Click" />

Step 5 : Add the following code to your Page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
            string connectionString = "Data Source=.SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM Employee";
                cmd.Connection = con;
                con.Open();

                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        private void ExportGridView(string fileName, string contentType)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            Response.Charset = "";
            Response.ContentType = contentType;

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Close();
            Response.End();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
             ExportGridView("GridData.xls", "application/vnd.ms-excel");
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            
        }