Thursday, December 22

Inline Editing of GridView Cell like YUI

In this article I will explain how to do inline editing of a cell in gridview like YUI. Onclick of any cell the control associated with that cell will open along with Save and Cancel. I have used textbox, radio button and dropdownlist control.


GridView Inline Editing of Cell

GridView Inline Editing of Cell

GridView Inline Editing of Cell

Let's see how we can achieve this in gridview.

Step 1:  Add scriptmanager in the aspx page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

Step 2: Add a gridview in the update panel.

 

<asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvEmployee_RowDataBound" ForeColor="#333333" ShowHeader="True" DataKeyNames="EmployeeId">      <Columns>
            
<asp:BoundField HeaderText="Employee Id" DataField="EmployeeId" SortExpression
="EmployeeId">
                  
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
            
</asp:BoundField
>
            
<asp:BoundField HeaderText="Employee Name" DataField="EmployeeName" SortExpression
="EmployeeName">
                  
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
            
</asp:BoundField
>
            
<asp:BoundField HeaderText="Designation" DataField="Designation" SortExpression
="Designation">
                  
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
            
</asp:BoundField
>
            
<asp:BoundField HeaderText="Location" DataField="Location" SortExpression
="Location">
                  
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
            
</asp:BoundField
>      </Columns>
      
<RowStyle BackColor="#EFF3FB"
/>
      
<AlternatingRowStyle BackColor="White"
/>
      
<HeaderStyle BackColor="Maroon" ForeColor="White"
/></asp:GridView>

Step 3: Add three divs inside the same update panel which holds gridview, first to place textbox along with save and cancel button, second to place dropdownlist along with save and cancel button and third to place radiobutton along with save and cancel button.

 

<div style="display: none; position: absolute; background-color: White; border: Solid 1px Black" id="divText">
      
<table
>
            
<tr
>
                  
<td colspan
="2">
                        
<asp:TextBox ID="txtEmployeeName" MaxLength="50" runat="server"></asp:TextBox
>
                  
</td
>
            
</tr
>
            
<tr
>
                  
<td
>
                        
<asp:Button ID="btnTextSave" OnClick="btnTextSave_Click" runat="server" Text
="Save"/>
                  
</td
>
                  
<td
>
                        
<asp:Button ID="btnTextCancel" runat="server" Text="Cancel" OnClientClick="return HideTextDiv();"
/>
                  
</td
>
            
</tr
>
      
</table
></div>
<div style="display: none; position: absolute; background-color: White; border: Solid 1px Black" id="divDropDownList">
      
<table
>
            
<tr
>
                  
<td colspan
="2">
                        
<asp:DropDownList ID="ddlLocation" runat
="server">
                              
<asp:ListItem Text="NY" Value="NY"></asp:ListItem
>
                              
<asp:ListItem Text="NJ" Value="NJ"></asp:ListItem
>
                              
<asp:ListItem Text="Bangalore" Value="Bangalore"></asp:ListItem
>
                              
<asp:ListItem Text="London" Value="London"></asp:ListItem
>
                              
<asp:ListItem Text="Washington" Value="Washington"></asp:ListItem
>
                              
<asp:ListItem Text="Kentucky" Value="Kentucky"></asp:ListItem
>
                        
</asp:DropDownList
>
                  
</td
>
            
</tr
>
            
<tr
>
                  
<td
>
                        
<asp:Button ID="btnDDLSave" runat="server" Text="Save" OnClick="btnDDLSave_Click"
/>
                  
</td
>
                  
<td
>
                        
<asp:Button ID="btnDDLCancel" runat="server" Text="Cancel" OnClientClick="return HideDDLDiv();"
/>
                  
</td
>
            
</tr
>
      
</table
></div>
<div style="display: none; position: absolute; background-color: White; border: Solid 1px Black" id="dirRdB">
      
<table
>
            
<tr
>
                  
<td colspan
="2">
                        
<asp:RadioButtonList ID="rdDesignation" runat
="server">
                              
<asp:ListItem Text="S/W Engg" Value="S/W Engg"></asp:ListItem
>
                              
<asp:ListItem Text="Sr. S/W Engg" Value="Sr. S/W Engg"></asp:ListItem
>
                              
<asp:ListItem Text="Architect" Value="Architect"></asp:ListItem
>
                              
<asp:ListItem Text="Manager" Value="Manager"></asp:ListItem
>
                        
</asp:RadioButtonList
>
                  
</td
>
            
</tr
>
            
<tr
>
                  
<td
>
                        
<asp:Button ID="btnRdB" runat="server" Text="Save" OnClick="btnRdB_Click"
/>
                  
</td
>
                  
<td
>
                        
<asp:Button ID="btnRdBCancel" runat="server" Text="Cancel" OnClientClick="return HideRdBDiv();"
/>
                  
</td
>
            
</tr
>
      
</table
></div>

Step 4: Add a hiddenfield in the aspx page which will hold the employeeid of the cell being edited.

<asp:HiddenField runat="server" ID="hidEmployeeId" />

Step 5: Add below javascript in the aspx page. EditCell method will be used to get the employeeid of the corresponding cell which has been clicked, celText will be used to populate the corresponding control of the cell, ctrlType will decide which div needs to be visible, rowNo and colNo will be used to position the div.
HideDDLDiv will hide the div containing dropdownlist. HideRdBDiv will hide the div containing radiobutton and HideTextDiv will hide the div containing text box.

<script language="javascript" type="text/javascript">


function EditCell(employeeID, celText, ctrlType, rowNo, colNo, evt) {
      var
cellPos;
      var grdCtl = document.getElementById('gvEmployee'
);
      cellPos = grdCtl.rows[rowNo].cells[colNo]
      document.getElementById('<%=hidEmployeeId.ClientID%>'
).value = employeeID;
      switch
(ctrlType) {
            case "TextBox"
:
                  divEmployee = document.getElementById("divText"
);
                  document.getElementById('txtEmployeeName'
).value = celText;
                  HideDDLDiv();
                  HideRdBDiv();
                  break
;
            case "DropDownList"
:
                  divEmployee = document.getElementById("divDropDownList"
);
                  document.getElementById("ddlLocation"
).value = celText;
                  HideTextDiv();
                  HideRdBDiv();
                  break
;
            case "RadioButton"
:
                  divEmployee = document.getElementById("dirRdB"
);
                  var radioButtons = document.getElementsByName("rdDesignation"
);
                  for (var
x = 1; x < radioButtons.length; x++) {
                        if
(radioButtons[x].value == celText) {
                              radioButtons[x].checked = true
;
                        }
                  }
                  HideTextDiv();
                  HideDDLDiv();
                  break
;
            }

            divEmployee.style.left = (cellPos.offsetLeft + 9) + "px"
;
            divEmployee.style.top = (cellPos.offsetTop + 9) + "px"
;
            divEmployee.style.display = ""
;
      }

      function
HideTextDiv() {
            var divEmployee = document.getElementById("divText"
);
            divEmployee.style.display = "none"
;
            return false
;
      }

      function
HideDDLDiv() {
            var divEmployee = document.getElementById("divDropDownList"
);
            divEmployee.style.display = "none"
;
            return false
;
      }

      function
HideRdBDiv() {
            var divEmployee = document.getElementById("dirRdB"
);
            divEmployee.style.display = "none"
;
            return false
;
      }
</script>

Step 6: Create a method GetData() which will return datatable to bind with gridview.

private DataTable GetData(string strQuery)
{
      DataTable dtDept = null
;
      SqlConnection
con = GetConnection();
      using
(con)
      {
            con.Open();
            using (SqlDataAdapter sqlAdapter = new SqlDataAdapter
(strQuery, con))
            {
                  dtDept = new DataTable
();
                  sqlAdapter.Fill(dtDept);
            }
      }
      return
dtDept;
}

private SqlConnection GetConnection()
{
      SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Speaks;Integrated Security=SSPI"
);
      return
con;
}

Step 7: Bind the data returned GetData() to gridview on !IsPostBack of page load.


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

private void BindGrid()
{
      string strQuery = "SELECT * FROM employee"
;
      gvEmployee.DataSource = GetData(strQuery);
      gvEmployee.DataBind();
}


Step 8: In RowDataBound event each cell needs to be bind with EditCell javascript method. The kind of control needs to be visible on click of EditCell has to be decided in rowdatabound based on the column.

protected void gvEmployee_RowDataBound(Object sender, GridViewRowEventArgs e)
{
      string ctrlType = string
.Empty;
      if (e.Row.RowType == DataControlRowType
.DataRow)
      {
            for (int
i = 1; i < gvEmployee.Columns.Count; i++)
            {
                  switch
(i)
                  {
                        case
1:
                              ctrlType = "TextBox"
;
                              break
;
                        case
2:
                              ctrlType = "RadioButton"
;
                              break
;
                        case
3:
                              ctrlType = "DropDownList"
;
                              break
;
                  }
                  DataKey
dk = gvEmployee.DataKeys[e.Row.DataItemIndex];
                  e.Row.Cells[i].Attributes.Add("onclick", "EditCell('" + dk.Values["EmployeeId"].ToString() + "','" + e.Row.Cells[i].Text + "','" + ctrlType + "','" + (e.Row.RowIndex + 1) + "','" + i + "');"
);
            }
      }
}


Step 9: Now we need to place three button events, first is associated with first column of gridview, second is associated with second coulmn of gridview and thrid is associated with third column of gridview.
protected void btnTextSave_Click(object sender, EventArgs e)
{
      string
empID = hidEmployeeId.Value;
      string strQuery = "UPDATE employee SET employeeName = '" + txtEmployeeName.Text + "' WHERE EmployeeID = "
+ hidEmployeeId.Value;
      UpdateTable(strQuery);
      BindGrid();
}

protected void btnRdB_Click(object sender, EventArgs e)
{
      string
empID = hidEmployeeId.Value;
      string strQuery = "UPDATE employee SET Designation = '" + rdDesignation.SelectedValue + "' WHERE EmployeeID = "
+ hidEmployeeId.Value;
      UpdateTable(strQuery);
      BindGrid();
}

protected void btnDDLSave_Click(object sender, EventArgs e)
{
      string
empID = hidEmployeeId.Value;
      string strQuery = "UPDATE employee SET Location = '" + ddlLocation.SelectedValue + "' WHERE EmployeeID = "
+ hidEmployeeId.Value;
      UpdateTable(strQuery);
      BindGrid();
}

Step 10: At last we need to place UpdateTable method which will be invoked by the above three button click methods.

private void UpdateTable(string strQuery)
{
      string m_conString = CryptographyHelper.Decrypt(ConfigurationSettings.AppSettings["DBConnectionString"
]);
      SqlConnection
con = GetConnection(m_conString);
      using
(con)
      {
            con.Open();
            SqlCommand cmd = new SqlCommand
(strQuery, con);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
      }
}



 
Live Demo
This ends the article of inline editing of a cell in gridview like YUI.
Like us if you find this post useful. Thanks! 
Shibashish mohanty
Download Code 

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty