Sunday, February 5, 2012

Quick Edit On DataGrid in ASP.Net + Javascript



Javascript Code :

<script type="text/javascript">

function QuickEdit(editbtnid, textboxid, savebtnid, linkbtnid, cancelbtnid)
{
            var QuestionText = document.getElementById(linkbtnid).innerText;
            document.getElementById(textboxid).value = QuestionText;
            document.getElementById(textboxid).style.display = "inline";
            document.getElementById(savebtnid).style.display = "inline";
            document.getElementById(cancelbtnid).style.display = "inline";
            editbtnid.style.display = "none";
            document.getElementById(linkbtnid).style.display = "none";
}

</script>


ASP.Net Code :

( EDIT Button )

<img id="imgedit" alt="edit" src="images/edit.png" onclick="QuickEdit(this,'<%# ((GridViewRow)Container).FindControl("txtQuestion").ClientID %>',
'<%# ((GridViewRow)Container).FindControl("imgbtnSave").ClientID %>',
'<%# ((GridViewRow)Container).FindControl("hypEvents").ClientID %>',
'<%# ((GridViewRow)Container).FindControl("imgbtnCancel").ClientID %>')" />


( SAVE Button )

<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Save" 
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
ImageUrl="images/save.png" Width="24px" Height="24px" Style="display: none;" />

( CANCEL Button )

<asp:ImageButton ID="imgbtnCancel" runat="server" mageUrl="images/cancel.png" Width="24px" Height="24px" Style="display: none;" />



C# Code :

protected void gvQuestion_RowCommand(object sender, GridViewCommandEventArgs e)
{
        if (e.CommandName == "Save")
        {
           //Write code for record update.
           AssessmentCon.Open();
           TextBox txtQuestion = (TextBox)gvQuestion.FindControl("txtQuestion");
           int index = Convert.ToInt32(e.CommandArgument);

           // Retrieve the row that contains the button clicked
           // by the user from the Rows collection.     
           GridViewRow row = gvQuestion.Rows[index];

 long questionID = Convert.ToInt32(  
 ((CheckBox)row.Cells[0].FindControl("chkQuestion")).ToolTip);
 string questionName =  
 ((TextBox)row.Cells[1].FindControl("txtQuestion")).Text;
SqlCommand cmd = new SqlCommand("Update AssessmentQuestionsMaster 
Set  AssessmentQuestionName ='" + questionName + "' Where AssessmentQuestionId = " + questionID ,AssessmentCon );

            cmd.Connection = AssessmentCon;
           
     int Del = cmd.ExecuteNonQuery();
           
            AssessmentCon.Close();

            gvQuestion.DataBind();
        }
    }