Showing posts with label DropDownList. Show all posts
Showing posts with label DropDownList. Show all posts

Sunday, 31 December 2017

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

In this article, I am going to explain you how to convert asp.net mvc dropdownlist into multi select textbox using Chosen JS plugin. You can see in below figure how the dropdown will look like after converting into multi select textbox.

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Adding Models

Go to Models folder and add new class file CountryData.cs. Now replace all code with below code. Here we have one list property CountryList which is type of SelectListItem for holding list of country data. Four string property for holding Id of 4 different dropdowns which we will see in article.

Share:

Saturday, 23 December 2017

Dropdown with Multi Select (Multiple selection) with checkbox using jQuery, Bootstrap and Multiselect JS

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) with dropdown (select option in html) using CheckBox with help of jQuery, Bootstrap and MultiSelect JS.

In HTML File

In html file, create a select list (dropdown) with multiple="multiple" and bind with some dummy data as shown below.
Here in script JS files, First file is jQuery file Second, Third is bootstrap JS, CSS files and Fourth, Fifth file is MultiSelect JS and CSS Files.
Make sure all files is loaded when application runs.

Share:

Sunday, 10 December 2017

Grid.MVC with MultiSelect DropDownList with CheckBox auto selected from database in MVC

In this tutorial, I am going to explain you bind how to bind multiple selection (MultiSelect) DropDownList with CheckBox in Grid.MVC in ASP.Net MVC from database using jQuery, Bootstrap and MultiSelect JS. I will be using Visual Studio 2013 and ADO.Net code to get data from SQL-Server Database.

As you can see in below screen-shot, multi-select dropdownlist is auto-selected. Here in Subject column , subject value is concatenated with comma from database, while binding to MVCGrid subject is auto selected in last column as shown below.

Grid.MVC with MultiSelect DropDownList with CheckBox auto selected from database in MVC

Creating Table and Procedure

Use below script to create a Student Table and procedure to fetch data from database.

Share:

Saturday, 21 October 2017

MVC MultiSelect (Multiple Selection) DropdownList with CheckBoxes Using jQuery

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) DropDownList with CheckBox in MVC using jQuery, Bootstrap and MultiSelect JS.

Creating MVC Model

First of all, we need to create model. Write click on Models folder and add a new class name as CountryModel. Replace all code with below code. CountryList property is used to store List of Country and SelCountry property is used to store selected country while passing to the controller.

Share:

Monday, 26 June 2017

Cascaded Dropdown in ASP.Net MVC using Entity Framework and jQuery ajax

In this article, I am going to teach you the basic cascading Dropdown in ASP.Net MVC using Entity Framework and jQuery Ajax. So, I am going to use Visual Studio 2013 ultimate, .net framework 4.5 and MVC version 4 and below is step by step tutorial.

Creating Database Table

First of all, we need to create database table. Below is the script to create two tables that are State Master and District Master and insert some dummy data into it.

create table tblStateMaster
(
StateId int,
Name varchar(100)
)
go
insert into tblStateMaster values(1,'Maharashtra')
insert into tblStateMaster values(2,'Gujarat')
go
create table tblDistrictMaster
(
DistId int,
StateId int,
Name varchar(100)
)
insert into tblDistrictMaster values(1,1,'Mumbai')
insert into tblDistrictMaster values(2,1,'Thane')
insert into tblDistrictMaster values(3,1,'Pune')
insert into tblDistrictMaster values(4,1,'Raigad')
go
insert into tblDistrictMaster values(5,2,'Ahmedabad')
insert into tblDistrictMaster values(6,2,'Rajkot')
insert into tblDistrictMaster values(7,2,'Gandhinagar')
insert into tblDistrictMaster values(8,2,'Vadodara')
Create table

Creating ASP.Net MVC Application

Now we need to create asp.net mvc application. Open Visual Studio 2013. Go to File --> New --> Project.. as shown below.

Creating a new asp.net mvc application

Go to Installed --> Templates --> Web --> Visual Studio 2012 and select .NET Framework 4.5 and ASP.NET MVC 4 Web Application as shown below.

Selecting asp.net mvc project

In the next window, select Empty template and click on OK and new MVC project will be created as shown below

Selecting asp.net mvc templateAsp.net mvc folder architecture

Adding Entity Framework

Now the next step is Entity Framework. Go to TOOLS --> Library Package Manager --> Manage NuGet Packages for Solution.. and a new window will open. Type and search for Entity Framework and click on Install button as shown below. Once installed successfully, you can check Entity Framework in references folder.

Adding Entity Framework
Installing Entity Framework

Adding Model

Now the next step is to add model. Go to Model and add two class files i.e. Data.cs and DataContext.cs. In Data.cs file, add below lines of code to map our database table to model object.

Adding modelAdding model and context class
[Table("tblStateMaster")]
public class State
{
    [Key]
    public int StateId { get; set; }
    public string Name { get; set; }
}

[Table("tblDistrictMaster")]
public class District
{
    [Key]
    public int DistId { get; set; }
    public int StateId { get; set; }
    public string Name { get; set; }
}

In DataContext.cs file, add two properties of type DbSet which will return DbSet of State and District.

Adding context class
public class DataContext : DbContext
{
    public DbSet<State> State { get; set; }
    public DbSet<District> District { get; set; }
}

Adding Connection String

Now add the connection string as shown below. Name of connection string should be same as context class name[DataContext].

Adding web.config file
Data context and web.config file connection string

Adding Controller

Now the next step is to add controller. Go to controller folder and add a new controller file named as DropDownController. Add below lines of code.

Adding controller class
public class DropDownController : Controller
{
    DataContext dc = new DataContext();

    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetState()
    {
        var stateData = dc.State.ToList().OrderBy(x => x.Name);
        return Json(stateData, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetDistrict(int StateId)
    {
        var districtData = dc.District.Where(x => x.StateId == StateId).OrderBy(x => x.Name);
        return Json(districtData);
    }
}

Adding jQuery File

Now the next step is to add jQuery file. You can download latest jQuery file from http://jquery.com/download/. Add jQuery file to your Scripts folder.

Adding View

Now the next step is to add View. Right click on Index ActionResult method, click Add View, give your View name as Index and do not click on strongly-typed view and click on Add. A DropDown folder will be added inside Views folder and an Index.cshtml file will be created.

Below is the code to Bind State Dropdown and District Dropdown using jQuery ajax method.

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">

    // bind State Dropdown when html is loaded
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/DropDown/GetState",
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlState').append('<option value="' + value.StateId + '">' + value.Name + '</option>');
                });
            }
        });
    });
    // bind State Dropdown when html is loaded

    // bind district Dropdown on selection change of State
    $(document).ready(function () {
        $('#ddlState').change(function () {
            $('#ddlDistrict').empty();
            $.ajax({
                type: "POST",
                url: "/DropDown/GetDistrict",
                datatype: "Json",
                data: { StateId: $('#ddlState').val() },
                success: function (data) {
                    $('#ddlDistrict').append('<option value>--Select--</option>');
                    $.each(data, function (index, value) {
                        $('#ddlDistrict').append('<option value="' + value.DistId + '">' + value.Name + '</option>');
                    });
                }
            });
        });
    });
    // bind district dropdownlist on Dropdown change of State
</script>

<h2>Cascading DropDownList Example</h2>
<table style="font-family:Arial;">
    <tr>
        <td>
            @Html.DropDownList("ddlState", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
        <td>
            @Html.DropDownList("ddlDistrict", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
    </tr>
</table>

Once View is loaded successfully, you can see expected output below.

Cascading dropdown in asp.net mvc
Share:

Sunday, 19 February 2017

ASP.Net GridView CRUD operations with Button controls outside of GridView control

In this article, we are going to learn CRUD operations that is insert, select, edit, update and delete with asp.net gridview control using sql stored procedure. I have already explained CRUD operations with stored procedure in one of my article, but in this article CRUD (Create, Read, Update, Delete) buttons will be residing outside of GridView control. You can see in below figures, button controls are residing below the gridview controls.

Crud operations in asp.net

Related Articles

  1. Insert, update, delete, crud operation in ASP.Net GridView with C# using Stored Procedure
  2. LINQ to SQL: GridView select, insert, update and delete using C# with ASP.Net

Creating SQL Table

First, we need to create two database tables. First for storing different City and second for storing employee's details. Below is the script to create table.

--creating city table
create table tblCity
(
Id int identity primary key,
Name varchar (50) null,
)
go
--inserting record into city table
insert into tblCity values('Mumbai')
insert into tblCity values('Delhi')
insert into tblCity values('London')
insert into tblCity values('New York')
go
--creating employee table
create table tblEmployee
(
Id int identity primary key,
Name varchar (50) null,
Gender varchar (10) null,
EMail varchar (25) null,
CityId int
)

Creating Standard Procedure

Also, we need to create stored procedure for different CRUD operations.

create procedure proc_Employee
@Action varchar(10)=null,
@Id int=null,
@Name varchar(50)=null,
@Gender varchar(10)=null,
@EMail varchar(25)=null,
@CityId int=null
as
begin
   if(@Action='Select')
      begin
       --to display all the record
       select e.Id,e.Name,e.Gender,e.EMail,c.Name as City from tblEmployee e
       join tblCity c on e.CityId=c.id
      end
   else if(@Action='Add')
     begin
      --to add a new record
      insert into tblEmployee values (@Name,@Gender,@EMail,@CityId) 
     end
   else if(@Action='Update')
     begin
      --to update the existing record
      update tblEmployee set Name=@Name,@Gender=@Gender,EMail=@EMail,CityId=@CityId where Id=@Id 
     end

   else if(@Action='Delete')
     begin
      --to delete a record
      delete from  tblEmployee where Id=@Id 
     end
   else if(@Action='GetCity')
     begin
      --to get all the city for binding dropdown control
      select Id,Name from tblCity
     end
end 

Creating Connection In Web.Config File

Write your database connection string in web.config file within <connectionStrings> tag.

<configuration>
  <connectionStrings>
<add name="MyConnString" connectionString="server=XXXX;database=XXXX;uid=XXXX;password=XXXX;" 
    providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

In Designer File

CSS For Buttons

In designer file, add css for button controls.

<head runat="server">
    <title></title>
    <style type="text/css">
        .button
        {
            border-radius: 0.5em;
            color: white;
            padding: 7px;
            background-color: #329bd8;
            text-transform: uppercase;
            font-weight: bold;
            width: 80px;
        }
        .button:hover
        {
            background-color: transparent;
            border: 0.15em #329bd8 solid;
            color: #329bd8;
        }
    </style>
</head>

Creating Gridview Control

Next step is create a GridView control gridEmployee with 5 columns. Generate OnPageIndexChanging event and DataKeyNames for storing Employee's ID. Create 5 button controls for Add, Edit, Update, Delete and Cancel purpose.

<form id="form1" runat="server">
 <div>
   <table>
     <tr>
     <td>
       <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
     </td>
     </tr>
     <tr>
     <td>
      <asp:GridView ID="gridEmployee" runat="server" PageSize="5" AutoGenerateColumns="false" 
          ShowFooter="true" AllowPaging="true" BackColor="White" BorderColor="#CC9966" 
          BorderStyle="None" BorderWidth="5px" CellPadding="4" 
          OnPageIndexChanging="gridEmployee_PageIndexChanging" Width="540px"
          DataKeyNames="Id">
          <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
          <RowStyle BackColor="White"/>
          <EditRowStyle BackColor="#FFFFCC" ForeColor="#330099" />
          <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
          <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
          <HeaderStyle BackColor="#329bd8" Font-Bold="True" ForeColor="White"/>
          <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="etxtName" runat="server" Text='<%#Eval("Name")%>'> </asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="ftxtName" runat="server"> </asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Gender">
                <ItemTemplate>
                    <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="eddlGender" runat="server">
                        <asp:ListItem Value="-Select-">-Select-</asp:ListItem>
                        <asp:ListItem Value="Male">Male</asp:ListItem>
                        <asp:ListItem Value="Female">Female</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="fddlGender" runat="server">
                        <asp:ListItem Value="-Select-">-Select-</asp:ListItem>
                        <asp:ListItem Value="Male">Male</asp:ListItem>
                        <asp:ListItem Value="Female">Female</asp:ListItem>
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="EMail">
                <ItemTemplate>
                    <asp:Label ID="lblEMail" runat="server" Text='<%#Eval("EMail")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="etxtEMail" runat="server" Text='<%#Eval("EMail")%>'> </asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="ftxtEMail" runat="server"> </asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="eddlCity" runat="server">
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="fddlCity" runat="server">
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
          </Columns>
      </asp:GridView>
     </td>
     </tr>
     <tr>
     <td>
       <table align="center">
         <tr style="width:500px;">
           <td>
               <asp:Button ID="btnAdd" runat="server" Text="Add" CssClass="button" OnClick="btnAdd_Click" />
           </td>
           <td>
               <asp:Button ID="btnEdit" runat="server" Text="Edit" CssClass="button" OnClick="btnEdit_Click" />
               <asp:Button ID="btnESave" runat="server" Text="Update" CssClass="button" OnClick="btnESave_Click" />
           </td>
           <td>
               <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="button" OnClick="btnDelete_Click" />
           </td>
           <td>
               <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="button" OnClick="btnCancel_Click" />
           </td>
         </tr>
       </table>
     </td>
     </tr>
   </table>
 </div>
</form>

Namespaces Used

Include the below Namespaces.

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

Complete C# Code

On the Page_Load event, we are calling GetCity() method which will fetch city data from tblCity table and store city data into static dataset dsCity so that we can use it later.

Next method is BindGrid() which will execute the stored procedure with Select action to fetch all employee's record. If no record is found then we are adding new row to empty dataset and binding it to GridView. Also we are binding City DropDownList in footer row using static dataset dsCity.

As footer row is always enabled, on click of Add button, btnAdd_Click event get fired. We are using GridView.FooterRow.FindControl() to find required TextBox and DropDownList controls and perform server side validation, if validation is successful then executing the stored procedure with Add action to save record into database.

Now, the next step is to Edit a record, we can edit only a single record at a time. We are storing editindex of required row in ViewState so that we can use later while updating the record. We are binding City DropDownList while editing using static dataset dsCity. Also disabling the CheckBox control.

On click of Update button, btnESave_Click event get fired. We are retrieving current row index using ViewState. After that retrieving Employee's Id using GridView.DataKeys. GridView.Rows[editindex].FindControl() is used find the respective TextBox and DropDownList controls. After that, we are calling stored procedure to update the record.

The last step is to Delete the record. Here, we can delete as many records we want by selecting CheckBox control. Main important thing while deleting is to fetch Employee's Id using editindex.

public partial class WebForm1 : System.Web.UI.Page
{
    //retrieving connection string from web.config file
    string MyConnString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
    SqlConnection con = null;
    SqlCommand cmd = null;
    public static DataSet dsCity=null;
    int editindex = -1;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            GetCity();
            BindGrid();
            // hide Update button on page load
            btnESave.Visible = false;             
        }
    }
 
    private void GetCity()
    {
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
 
        // call the GetCity task to get all Cities
        cmd.Parameters.AddWithValue("@Action", "GetCity");
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
 
        dsCity = ds.Copy(); // copy city data into static dataset         
    }
 
    private void BindGrid()
    {
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        // call the select task to get all data
        cmd.Parameters.AddWithValue("@Action", "Select");
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            gridEmployee.DataSource = ds;
            gridEmployee.DataBind();
        }
        else
        {
            // add new row when the dataset is having zero record
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gridEmployee.DataSource = ds;
            gridEmployee.DataBind();
            gridEmployee.Rows[0].Visible = false;
        }
 
        // find the FooterRow City dropdown and populate it from static dataset
        DropDownList fddlCity = (DropDownList)gridEmployee.FooterRow.FindControl("fddlCity");
        if (dsCity.Tables[0].Rows.Count > 0)
        {
            fddlCity.DataSource = dsCity.Tables[0];
            fddlCity.DataTextField = "Name";
            fddlCity.DataValueField = "Id";
            fddlCity.DataBind();
            fddlCity.Items.Insert(0, "-Select-");
        }
    }
 
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        TextBox ftxtName = (TextBox)(gridEmployee.FooterRow.FindControl("ftxtName"));
        DropDownList fddlGender = (DropDownList)(gridEmployee.FooterRow.FindControl("fddlGender"));
        TextBox ftxtEMail = (TextBox)(gridEmployee.FooterRow.FindControl("ftxtEMail"));
        DropDownList fddlCity = (DropDownList)(gridEmployee.FooterRow.FindControl("fddlCity"));
 
        if (ftxtName.Text.Trim() == string.Empty)
        {
            lblMessage.Text = "Please enter Name";
            ftxtName.Focus();
            return;
        }
        if (fddlGender.SelectedIndex==0)
        {
            lblMessage.Text = "Please select Gender";
            fddlGender.Focus();
            return;
        }
        if (!Regex.IsMatch(ftxtEMail.Text.Trim(), @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
        , RegexOptions.IgnoreCase))
        {
            lblMessage.Text = "Please enter valid EMail";
            ftxtEMail.Focus();
            return;
        }
        if (fddlCity.SelectedIndex==0)
        {
            lblMessage.Text = "Please select City";
            fddlCity.Focus();
            return;
        }
 
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        // call the select task to get all data
        cmd.Parameters.AddWithValue("@Action", "Add");
        cmd.Parameters.AddWithValue("@Name", ftxtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Gender", fddlGender.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@EMail", ftxtEMail.Text.Trim());
        cmd.Parameters.AddWithValue("@CityId", fddlCity.SelectedItem.Value);          
        cmd.ExecuteNonQuery();
        con.Close();
        BindGrid();           
        lblMessage.Text = "Record saved successfully";
    }
 
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        int rowCount = 0;
        foreach (GridViewRow gvrow in gridEmployee.Rows)
        {
            CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
            if (chkRow.Checked && chkRow != null)
            {
                //finding rowindex for edit
                editindex = gvrow.RowIndex;
                rowCount++;
                if (rowCount>1)
                {
                    break;
                }
            }
        }
        if (rowCount>1)
        {
            lblMessage.Text = "Please select single record to Edit";
        }
        else if(rowCount==0)
        {
            lblMessage.Text = "Please select record to Edit";
        }
        else
        {
            ViewState["editindex"] = editindex;
 
            gridEmployee.EditIndex = editindex;
            BindGrid();
 
            // bind city dropdown while editing
            DropDownList eddlCity = (DropDownList)(gridEmployee.Rows[editindex].FindControl("eddlCity"));
            if (dsCity.Tables[0].Rows.Count > 0)
            {
                eddlCity.DataSource = dsCity.Tables[0];
                eddlCity.DataTextField = "Name";
                eddlCity.DataValueField = "Id";
                eddlCity.DataBind();
                eddlCity.Items.Insert(0, "-Select-");
            }
 
            // disable all row checkboxes while editing
            foreach (GridViewRow gvrow in gridEmployee.Rows)
            {
                CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
                chkRow.Enabled = false;
            }
 
            //hide footer row while editing
            gridEmployee.FooterRow.Visible = false;
 
            // hide and disable respective buttons
            btnAdd.Enabled = false;
            btnEdit.Visible = false;
            btnESave.Visible = true;
            btnDelete.Enabled = false;            
        }
    }
 
    protected void btnESave_Click(object sender, EventArgs e)
    {
        // retrieving current row edit index from viewstate
        editindex= Convert.ToInt32(ViewState["editindex"].ToString());
 
        int Id = Convert.ToInt32(gridEmployee.DataKeys[editindex].Values["Id"].ToString());
        TextBox etxtName = (TextBox)gridEmployee.Rows[editindex].FindControl("etxtName");
        DropDownList eddlGender = (DropDownList)(gridEmployee.Rows[editindex].FindControl("eddlGender"));
        TextBox etxtEMail = (TextBox)(gridEmployee.Rows[editindex].FindControl("etxtEMail"));
        DropDownList eddlCity = (DropDownList)(gridEmployee.Rows[editindex].FindControl("eddlCity"));
 
        if (etxtName.Text.Trim() == string.Empty)
        {
            lblMessage.Text = "Please enter Name";
            etxtName.Focus();
            return;
        }
        if (eddlGender.SelectedIndex == 0)
        {
            lblMessage.Text = "Please select Gender";
            eddlGender.Focus();
            return;
        }
        if (!Regex.IsMatch(etxtEMail.Text.Trim(), @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
        , RegexOptions.IgnoreCase))
        {
            lblMessage.Text = "Please enter valid EMail";
            etxtEMail.Focus();
            return;
        }
        if (eddlCity.SelectedIndex == 0)
        {
            lblMessage.Text = "Please select City";
            eddlCity.Focus();
            return;
        }
 
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        // call the update task
        cmd.Parameters.AddWithValue("@Action", "Update");
        cmd.Parameters.AddWithValue("@Id", Id);
        cmd.Parameters.AddWithValue("@Name", etxtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Gender", eddlGender.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@EMail", etxtEMail.Text.Trim());
        cmd.Parameters.AddWithValue("@CityId", eddlCity.SelectedItem.Value);
        cmd.ExecuteNonQuery();
        con.Close();
 
        gridEmployee.EditIndex = -1;
        BindGrid();
 
        lblMessage.Text = "Record updated successfully";
 
        btnAdd.Enabled = true;
        btnEdit.Visible = true;
        btnESave.Visible = false;
        btnDelete.Enabled = true;
 
    }
 
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int rowCount = 0;
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
 
        foreach (GridViewRow gvrow in gridEmployee.Rows)
        {
            CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
            if (chkRow.Checked && chkRow != null)
            {
                //finding rowindex for delete
                editindex = gvrow.RowIndex;
 
                // retrieve Id from DataKeys to delete record
                int Id = Convert.ToInt32(gridEmployee.DataKeys[editindex].Values["Id"].ToString());
 
                // call the delete task
                cmd.Parameters.AddWithValue("@Action", "Delete");
                cmd.Parameters.AddWithValue("@Id", Id);
 
                cmd.ExecuteNonQuery();
                // clear parameter after every delete
                cmd.Parameters.Clear();
 
                rowCount++;
            }
        }
        con.Close();
 
        if (rowCount > 0)
        {
            lblMessage.Text = "Record deleted successfully";
            BindGrid();
        }
        else
        {
            lblMessage.Text = "Select record to Delete";
        }
    }
 
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        gridEmployee.EditIndex = -1;
        BindGrid();
 
        btnAdd.Enabled = true;
        btnEdit.Visible = true;
        btnESave.Visible = false;
        btnDelete.Enabled = true;           
    }
 
    protected void gridEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridEmployee.PageIndex = e.NewPageIndex;
        BindGrid();
        lblMessage.Text = "";
    }
}
Share:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

Ads By Chitika