1
votes

I have a Gridview in ASP.NET where I need to include checkbox to the gridview and an Update button. On checking the checkbox for a particular row, the update event should trigger and clicking the update button should save the changes. I have written C# code to update the Gridview without using the checkbox. However, unable to proceed when the checkbox is included. Grid View Design Code is :

    <%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Employee ID"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server" style="margin-left: 110px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Employee Name"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" style="margin-left: 90px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label3" runat="server" Text="Employee Experience"></asp:Label>
        <asp:TextBox ID="TextBox3" runat="server" style="margin-left: 61px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label4" runat="server" Text="Employee Address"></asp:Label>
        <asp:TextBox ID="TextBox4" runat="server" style="margin-left: 79px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
            style="text-align: left" Text="Submit" />
    <asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="Emp_id" onrowcancelingedit="EmployeeGridView_RowCancelingEdit" 
            onrowediting="EmployeeGridView_RowEditing" 
            onrowdeleting="EmployeeGridView_RowDeleting" 
            onrowupdating="EmployeeGridView_RowUpdating" AllowPaging="True" CellPadding="4" 
            ForeColor="#333333" GridLines="None" 
            onpageindexchanging="EmployeeGridView_PageIndexChanging" 
            Width="408px" AllowSorting="True" 
            onselectedindexchanged="EmployeeGridView_SelectedIndexChanged">   
        <AlternatingRowStyle BackColor="White" />
    <Columns>
    <asp:TemplateField HeaderText="Sr.No">
    <ItemTemplate><%#Container.DataItemIndex+1 %></ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate><%#Eval("Emp_name") %></ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Emp_name") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>    
     <asp:TemplateField HeaderText="Experience">
    <ItemTemplate><%#Eval("Emp_exp") %></ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtempexp" runat="server" Text='<%#Eval("Emp_exp") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>
     <asp:TemplateField HeaderText="Address">
    <ItemTemplate><%#Eval("Emp_address") %></ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtempaddress" runat="server" Text='<%#Eval("Emp_address") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>

  <asp:CommandField ShowEditButton="true" ButtonType ="Button" 
            ItemStyle-ForeColor= "Aqua">
<ItemStyle ForeColor="Aqua"></ItemStyle>
        </asp:CommandField>
  <asp:CommandField ShowDeleteButton="true" ButtonType="Button" HeaderText="Delete" />  
    </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerSettings FirstPageText="First" LastPageText="Last" 
            Mode="NumericFirstLast" PageButtonCount="4" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>


    </div>
    <asp:Button ID="Button1" runat="server" Text="Update" />
    </form>
</body>
</html>

C# code Behind is :

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


public partial class _Default : System.Web.UI.Page
{
    string connstr = @"Data Source=xxxxxxx\SQLEXPRESS;Initial Catalog=xxxxxxxxx;Integrated Security=True";
    protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        Session["sortBy"] = e.SortExpression;
        FillGrid();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["sortBy"] = null;
        if (!Page.IsPostBack)
        {
            FillGrid();
        }
    }
    public void FillGrid()
    {
        SqlConnection con = new SqlConnection(connstr);
        con.Open();
        SqlCommand cmd = new SqlCommand("GetEmployeeInfo", con);
        SqlDataReader dr = cmd.ExecuteReader();//it reads froword only data from database
        DataTable dt = new DataTable();//object of data table that uses to conatin whole data
        dt.Load(dr);//Sql Data reader data load in data table it is DataTable Method.
        EmployeeGridView.DataSource = dt;
        EmployeeGridView.DataBind();

    }
    protected void EmployeeGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        EmployeeGridView.EditIndex = -1;
        FillGrid();

    }
    protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        EmployeeGridView.EditIndex = e.NewEditIndex;
        FillGrid();
    }

    protected void EmployeeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
        string name = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempname")).Text;//get TextBox Value in EditItemTemplet that row is clicked
        string experience = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempexp")).Text;
        string address = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempaddress")).Text;
        SqlConnection con = new SqlConnection(connstr);
        con.Open();
        SqlCommand cmd = new SqlCommand("EmployeeUpdate", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@emp_id ", empid);
        cmd.Parameters.AddWithValue("@emp_name ", name);
        cmd.Parameters.AddWithValue("@emp_exp ", experience);
        cmd.Parameters.AddWithValue("@emp_address ", address);
        cmd.ExecuteNonQuery();//Sql Command Class method return effected rows use for insert,update, delete
        EmployeeGridView.EditIndex = -1;// no row in edit mode
        FillGrid();
    }
    protected void EmployeeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());
        SqlConnection con = new SqlConnection(connstr);
        con.Open();
        SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@emp_id ", empid);
        cmd.ExecuteNonQuery();
        FillGrid();

    }
    protected void EmployeeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        EmployeeGridView.PageIndex = e.NewPageIndex;
        FillGrid();

    }
    private void UpdateOrAddNewRecord(string Emp_id, string Emp_name, string Emp_exp, string Emp_address)
    {
        SqlConnection con = new SqlConnection(connstr);
        string sqlStatement = string.Empty;
        sqlStatement = "INSERT INTO tbl_employee" +
                       "(Emp_id, Emp_name, Emp_exp, Emp_address)" +
                       "VALUES (@Emp_id, @Emp_name, @Emp_exp, @Emp_address)";
        con.Open();
        SqlCommand cmd = new SqlCommand(sqlStatement, con);
        cmd.Parameters.AddWithValue("@Emp_id", Emp_id);
        cmd.Parameters.AddWithValue("@Emp_name", Emp_name);
        cmd.Parameters.AddWithValue("@Emp_exp", Emp_exp);
        cmd.Parameters.AddWithValue("@Emp_address", Emp_address);
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
        con.Close();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        UpdateOrAddNewRecord(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text);
        FillGrid();
    }
}

I didnt keep the code for stored procedures of DeleteEmployee, EmployeeUpdate, GetEmployeeInfo.

In the above code I need to insert checkbox for the gridview and update the items which are checked instead of clicking Edit Button and then Updating

1
Paste your work here.. People can't read your mind..Soner Gönül
What exactly is your problem? What happens once you add a checkbox?Blachshma
I need code to keep checkboxes for every row and once the checkbox is checked and the Update button below is clicked for the selected checkbox , should prompt the user to enter the respective fields and then a save button to save.user1292831
I have a gridview checkboxes, and one button outside the gridview. I need to update the the gridview row values for the selected checkboxes to the database. i.e., I just want to get the row values for which the specific checkbox is selected and then insert/update those values to the table in database. Can you please suggest me regarding this?user1292831

1 Answers

2
votes

At the Event of Update Button Clicked Do these things. Loop through each Row of the grid. In each row, get the Respective Checked Box Check if CheckedBox is checked or not If it is checked then retrieve other values from the current row and call ur update method.

 for (int innercounter = 0; innercounter < grid.Rows.Count; innercounter++)
 {
CheckBox chkSelect;
chkSelect = (CheckBox)grid.Rows[innercounter].Cells[0].FindControl("ChkSelect");
if (chkSelect.Checked == true)
  {
     Label Field1 = (Label)grid.Rows[innercounter].Cells[1].FindControl("txtFieldName1");
     Label Field2 = (Label)grid.Rows[innercounter].Cells[2].FindControl("txtFieldName2");
     Update(Field1.text,Field2.text)
  }

}