Inline Editing and Updating in GridView with check box

Introduction

Editing and updating in gridview is very simple. But how can you edit when you use checkbox.

GirdView contain CheckBoxField that display checkbox in each item in GridView control. This column Fields is commonly use to display field with Boolean value.

  • If you use SQL SERVER and the Datatype for this field is bit then no problem for binding CheckBoxField data in GridView.
  • But you Datatype char(1) or anything and you insert like "T" or "F" then CheckBoxField is not bind.
  • Hear we can see how to solve this type of problem.

Step 1. Your .aspx page like this.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Untitled Page</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div align="center">  
        <table align="center">  
            <tr>  
                <td>  
                    <asp:GridView ID="gvuserinfo" runat="server" AllowPaging="True" AutoGenerateColumns="False"  
                        AutoGenerateEditButton="True"  
                        OnPageIndexChanging="gvuserinfo_PageIndexChanging"  
                        onrowcancelingedit="gvuserinfo_RowCancelingEdit"  
                        onrowediting="gvuserinfo_RowEditing"  
                        onrowupdating="gvuserinfo_RowUpdating">  
                        <Columns>  
                            <asp:BoundField DataField="userid" HeaderText="Userid" ReadOnly="True" >                                 
                            </asp:BoundField>  
                            <asp:BoundField HeaderText="User Name" DataField="username" />  
                            <asp:CheckBoxField DataField="allowplan" Text="" HeaderText="Allowed For Plan" />                            
                        </Columns>  
                    </asp:GridView>  
                </td>                 
            </tr>  
            <tr>  
                <td>  
                    <asp:Label ID="lblmessage" runat="server" ForeColor="Red"></asp:Label>  
                </td>  
            </tr>  
        </table>  
    </div>  
    </form>  
</body>  
</html>

Step 2. your .cs file like this.

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

#region :: Add using ::  
using System.Collections;  
#endregion  
  
public partial class _Default : System.Web.UI.Page  
{  
    #region :: Variable Declaration::  
      // DataAccess Class.  
    clsGeneral objGeneral = new clsGeneral();  
    #endregion  
    protected void Page_Load(object sender, EventArgs e)  
    {  
        if (!IsPostBack)  
        {  
            //Bind The Gridview.  
            BindGridView();  
        }  
    }  

    #region :: Bind GridView ::  
    private void BindGridView()  
    {  
        string connection = objGeneral.Getconnection();  
        string sql = "SELECT userid, username, allowforfreeplan FROM UserInfo ORDER BY username";  
        DataTable dtUserInfo = new DataTable();  
        dtUserInfo = objGeneral.SelectRows(dtUserInfo, connection, sql);  
  
        /*Create new column for database. 
         * this column is user for bind  ChecBoxField. 
        */  
        DataColumn column = new DataColumn();  
        column.DataType = System.Type.GetType("System.Boolean");  
        column.ColumnName = "allowplan";  
  
        //Add column in table.  
  
        dtUserInfo.Columns.Add(column);  
  
        if ((dtUserInfo != null) && (dtUserInfo.Rows.Count > 0))  
        {  
                        for (int i = 0; i < dtUserInfo.Rows.Count; i++)  
            {  
                string type = dtUserInfo.Rows[i]["allowforfreeplan"].ToString().ToUpper();  
                if (type == "T")  
                {  
                    dtUserInfo.Rows[i]["allowplan"] = true;  
                }  
                else  
                {  
                    dtUserInfo.Rows[i]["allowplan"] = false;  
                }  
            }  
            gvuserinfo.DataSource = dtUserInfo;  
            gvuserinfo.DataBind();  
        }  
    }  
    #endregion  
    protected void gvuserinfo_PageIndexChanging(object sender, GridViewPageEventArgs e)  
    {  
        gvuserinfo.PageIndex = e.NewPageIndex;  
        BindGridView();  
    }  
    protected void gvuserinfo_RowEditing(object sender, GridViewEditEventArgs e)  
    {  
        gvuserinfo.EditIndex = e.NewEditIndex;  
        BindGridView();  
    }  
    protected void gvuserinfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
    {  
        gvuserinfo.EditIndex = -1;  
        BindGridView();  
    }  
    protected void gvuserinfo_RowUpdating(object sender, GridViewUpdateEventArgs e)  
    {  
        int userid = Convert.ToInt32(gvuserinfo.Rows[e.RowIndex].Cells[1].Text);  
        TextBox txtname = (TextBox)gvuserinfo.Rows[e.RowIndex].Cells[2].Controls[0];  
        CheckBox cb = (CheckBox)gvuserinfo.Rows[e.RowIndex].Cells[3].Controls[0];  
        string allowforfree = string.Empty;  
  
        if (cb.Checked == true)  
        {  
            allowforfree = "T";  
        }  
        else  
        {  
            allowforfree = "F";  
        }  
        string sql = "UPDATE [dbo].[UserInfo]  SET [username] = '" + txtname.Text + "',[allowforfreeplan] = '" + allowforfree + "'";  
        sql += " WHERE  [dbo].[UserInfo].[userid] = " + userid;  
        string connection = objGeneral.Getconnection();  
        int i = objGeneral.InsertUpdateData(connection, sql);  
        if (i == 1)  
        {  
           // lblmessage.Text = "Record Updated Succesfully ...";  
        }  
        gvuserinfo.EditIndex = -1;  
        BindGridView();  
    }  
  
} 

Step 3. Your DataAccess Class like.

using System;  
using System.Data;  
using System.Configuration;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.HtmlControls;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Data.SqlClient;  
  
/// <summary>  
/// Summary description for clsGeneral  
/// </summary>  
public class clsGeneral  
{  
    protected string test = ConfigurationManager.ConnectionStrings["SQLCONNECTION"].ToString();  
      public clsGeneral()  
      {  
            //  
            // TODO: Add constructor logic here  
            //  
      }  
   
    public string Getconnection()  
    {  
        return test;  
    }  
  
    public  DataTable SelectRows(DataTable datatable,string connectionString, string queryString)  
    {  
        using (SqlConnection connection = new SqlConnection(connectionString))  
        {  
            SqlDataAdapter adapter = new SqlDataAdapter();  
            adapter.SelectCommand = new SqlCommand(queryString, connection);  
            adapter.Fill(datatable);  
            return datatable;  
        }  
    }  
  
    public int InsertUpdateData(string connectionString,string sql)  
    {  
        int i;  
        using (SqlConnection connection = new SqlConnection(connectionString))  
        {  
            connection.Open();  
            SqlCommand com = new SqlCommand(sql, connection);  
            i = com.ExecuteNonQuery();  
            return i;  
        }  
  
    }  
} 

You Can read my other article on http://www.c-sharpcorner.com


Similar Articles