Disable ASP.Net GridView RowCommand event based on condition using C# and VB.Net

Last Reply one month ago By pandeyism

Posted one month ago

i have this difficulty in creating the syntax for disabling rowcommand. 

As you can see in the code, I am using RowCommand for row selection in the gridview. I also have edit,save and cancel function. I just want to achieve this: If I click on Edit button, the row selection should be disable, meaning the user cannot select any other row inside the gridview while on the edit mode. Hope you can help me, thanks in advance

this is the code behind:

        protected void grdRecentCases_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
                e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdRecentCases, "Select$" + e.Row.RowIndex);
            }
        }


        protected void grdRecentCases_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                LoadData(Convert.ToInt32(e.CommandArgument));
            }
        }

        ///<summary> LoadData is used to populate inputboxes with the value of the selected griview row</summary>
        ///<param name="rowNumber"> Indicates whether there is a selected row or non</param>
        private void LoadData(int? rowNumber = null)
        {
            //if rowNumber is null use GridView1.SelectedIndex
            var index = rowNumber ?? grdRecentCases.SelectedIndex;

            //Populate the input box with the value of selected row.
            GridViewRow gr = grdRecentCases.Rows[index];
            txtDepartmentCase.Text = gr.Cells[2].Text;
            txtDepartment.Text = gr.Cells[3].Text;
            txtCharge.Text = gr.Cells[4].Text;
            txtLabCase.Text = gr.Cells[5].Text;
            txtIncidentReportDate.Text = gr.Cells[6].Text;
            txtCaseKey.Text = gr.Cells[1].Text;
        }


        protected void drpDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {   //Use to pass the selected value item inside the dropdownlist.
            drpDepartment.SelectedValue = drpDepartment.SelectedItem.Value;
            drpCharge.SelectedValue = drpCharge.SelectedItem.Value;
        }
        protected void drpCharge_SelectedIndexChanged(object sender, EventArgs e)
        {   //Use to pass the selected value item inside the dropdownlist.
            drpCharge.SelectedValue = drpCharge.SelectedItem.Value;
        }


        protected void btnEdit_Click(object sender, EventArgs e)
        {
            EnableDisableControls(true);
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            EnableDisableControls(false);

            string connStr = ConfigurationManager.ConnectionStrings["****ConnectionString"].ConnectionString;
            var cnn = new SqlConnection(connStr);
            cnn.Open();
            SqlCommand cmd = new SqlCommand("Update TV_LABCASE Set DEPARTMENT_CASE_NUMBER=@DEPARTMENT_CASE_NUMBER,DEPARTMENT_CODE=@DEPARTMENT_NAME,OFFENSE_CODE=@OFFENSE_DESCRIPTION,LAB_CASE=@LAB_CASE,OFFENSE_DATE=@OFFENSE_DATE where CASE_KEY=@CASE_KEY", cnn);
            cmd.Parameters.AddWithValue("@DEPARTMENT_CASE_NUMBER", txtDepartmentCase.Text);
            cmd.Parameters.AddWithValue("@DEPARTMENT_NAME", drpDepartment.SelectedValue);
            cmd.Parameters.AddWithValue("@OFFENSE_DESCRIPTION", drpCharge.SelectedValue);
            cmd.Parameters.AddWithValue("@LAB_CASE", txtLabCase.Text);
            cmd.Parameters.AddWithValue("@OFFENSE_DATE", txtIncidentReportDate.Text);
            cmd.Parameters.AddWithValue("@CASE_KEY", txtCaseKey.Text);
            cmd.ExecuteNonQuery();
            txtDepartment.Text = drpDepartment.SelectedItem.Text;
            txtCharge.Text = drpCharge.SelectedItem.Text;
            grdRecentCases.DataBind();
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            EnableDisableControls(false);
            LoadData();

        }

        ///<summary> define the editing state to determine which behavior of buttons/inputbox/dropdown to manipulate.</summary>
        ///<param name="editable"  type="button;text;dropdown"> Editing State</param>
        private void EnableDisableControls(bool editable)
        {
            btnEdit.Enabled = !editable;
            btnSave.Enabled = editable;
            btnCancel.Enabled = editable;
            txtDepartmentCase.Enabled = editable;
            txtLabCase.Enabled = editable;
            txtIncidentReportDate.Enabled = editable;
            txtDepartment.Visible = !editable;
            txtCharge.Visible = !editable;
            drpDepartment.Visible = editable;
            drpCharge.Visible = editable;
            drpDepartment.Enabled = editable;
            drpCharge.Enabled = editable;
        }
Posted one month ago Modified on one month ago

Hi leoduuude,

Refer below sample.

HTML

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:GridView ID="grdRecentCases" runat="server" AutoGenerateColumns="False" OnRowCommand="grdRecentCases_RowCommand"
    OnRowDataBound="grdRecentCases_RowDataBound">
    <Columns>
        <asp:ButtonField ButtonType="Link" CommandName="Select" Text="Select" Visible="true" />
        <asp:BoundField DataField="Item" HeaderText="Item" ReadOnly="True" SortExpression="v"
            Visible="true" />
        <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
    </Columns>
</asp:GridView>
<br />
<asp:Label ID="lblCaseDetails" runat="server" Font-Bold="True" Font-Names="Arial"
    Font-Size="Small" Text="Case Details"></asp:Label>
<br />
<asp:UpdatePanel ID="upCaseDetails" runat="server">
    <ContentTemplate>
        <table class="style2">
            <tr>
                <td class="style3">
                    Item
                </td>
                <td>
                    <asp:TextBox ID="txtItem" runat="server" Enabled="False"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Price
                </td>
                <td>
                    <asp:TextBox ID="txtPrice" runat="server" Enabled="False"></asp:TextBox>
                </td>
            </tr>
        </table>
    </ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="Edit" Enabled="false" />&nbsp;
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" Enabled="false" />&nbsp;
<asp:Button ID="btnCancel" runat="server" OnClick="btnCancel_Click" Text="Cancel"
    Enabled="false" />
<br />

Namespaces

C#

using System.Data;

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Price") });
        dt.Rows.Add("Shirt", 450);
        dt.Rows.Add("Jeans", 3200);
        dt.Rows.Add("Trousers", 1900);
        Session["buy"] = dt;
        grdRecentCases.DataSource = dt;
        grdRecentCases.DataBind();
    }
}

protected void grdRecentCases_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
        int indexx = grdRecentCases.SelectedIndex;
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = grdRecentCases.Rows[index];
        txtItem.Text = row.Cells[1].Text;
        txtPrice.Text = row.Cells[2].Text;
        EnableDisableControls(true);
            
    }
}

private void EnableDisableControls(bool editable)
{
    btnEdit.Enabled = editable;
    btnSave.Enabled = !editable;
    btnCancel.Enabled = !editable;
    txtItem.Enabled = editable;
    txtPrice.Enabled = editable;
}

protected void btnSave_Click(object sender, EventArgs e)
{
    grdRecentCases.Columns[0].Visible = true;
    foreach (GridViewRow row in grdRecentCases.Rows)
    {
        LinkButton btn = row.Cells[0].Controls[0] as LinkButton;
        btn.Enabled = true;
        EnableSelection(row);
    }
}

private void EnableSelection(GridViewRow row)
{
    row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
    row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
    row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdRecentCases, "Select$" + row.RowIndex);
}

protected void grdRecentCases_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        EnableSelection(e.Row);
    }
}

protected void btnEdit_Click(object sender, EventArgs e)
{
    int index = grdRecentCases.SelectedIndex;
    foreach (GridViewRow row1 in grdRecentCases.Rows)
    {
        if (index != row1.RowIndex)
        {
            LinkButton btn = row1.Cells[0].Controls[0] as LinkButton;
            btn.Enabled = false;
            row1.Attributes.Remove("onmouseover");
            row1.Attributes.Remove("onmouseout");
            row1.Attributes.Remove("onclick");
        }
    }
    if (btnEdit.Text.ToUpper() == "EDIT")
    {
        EnableDisableControls(false);
    }
    else
    {
        EnableDisableControls(true);
    }
}

protected void btnCancel_Click(object sender, EventArgs e)
{

}

Screenshot