Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if row modified in gridview

I have a GridView and I'm performing a bulk update for only one column with textbox. But before update I need to check the values of that textbox for entire gridview and if the values aren't changed I need to provide an alert stating "Make change to field to update".

Can anyone suggest me some options?

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (GridViewRow row in gvDetails.Rows)
            {
               string strID = ((Label)row.FindControl("lblID")).Text;
               string strGroup = ((Label)row.FindControl("lblGrp")).Text;
               string strValue = ((TextBox)row.FindControl("txtValue")).Text;                                     
               {
                   //my update query
               }
            }
        }
        catch (Exception ex)
        {

        }
    }
like image 305
Michael Avatar asked Apr 22 '15 07:04

Michael


2 Answers

A much simpler method will be to add an asp:HiddenField to your ItemTemplate and compare the value for each row.

<asp:HiddenField ID="" runat="server" Value='<%# Eval("blah") %>'></asp:HiddenField>

Now all you need is to compare that value with the textbox value in each row in code-behind like this.

protected void btnUpdate_Click(object sender, EventArgs e)
{
    try
    {
        var isAnyRowUpdated = false;
        foreach (GridViewRow row in gvDetails.Rows)
        {
            string strID = ((Label)row.FindControl("lblID")).Text;
            string strGroup = ((Label)row.FindControl("lblGrp")).Text;
            string strValue = ((TextBox)row.FindControl("txtValue")).Text;
            string strOldValue = ((HiddenField)row.FindControl("hdnOldValue")).Value;
            if (strValue != strOldValue)
            {
                isAnyRowUpdated = true;
                //update procedure here.
            }
        }
        //now check if the flag is still false
        //that means no rows are changed
        if(!isAnyRowUpdated)
        {
            //alert no rows are updated
        }
    }
    catch (Exception ex)
    {

    }
}

I hope the code is self explanatory.

like image 189
naveen Avatar answered Nov 17 '22 23:11

naveen


You can try to use DataGridView.RowValidating Event and check if IsCurrentRowDirty Property is changed

IsCurrentRowDirty Property Gets a value indicating whether the current row has uncommitted changes.

EDIT:-

The above works in Winforms; in Asp.net there is no such method, you have to load the data in a object and then you have to validate.

You can check Updating Only Changed Rows Using GridView Control

like image 37
Rahul Tripathi Avatar answered Nov 18 '22 00:11

Rahul Tripathi