I have a gridView with 5 columns with Edit and Delete button on each row of GridView. Once an Edit button a particular row is clicked , I want to disable the edit and delete buttons on rest of the rows.
Below is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="True" EnableModelValidation="True" onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting" EditRowStyle-ForeColor="Aqua" onrowediting="GridView1_RowEditing" >
<asp:TemplateField HeaderText="Item#" >
<ItemTemplate>
<asp:Label ID="Item#" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
..........
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" CausesValidation ="false" Font-Size="Smaller" CommandName="Edit" Text="Edit" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' Width="35px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CssClass="GridButton" CausesValidation="False" CommandName="Delete" Font-Size="Smaller" Text="Delete" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int x = Convert.ToInt32(e.CommandArgument.ToString());
txtLineItemNumber.Text = (x + 1).ToString();
}
else
{
int x = Convert.ToInt32(e.CommandArgument.ToString());
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex != x)
{
Button editButton = (Button)row.FindControl("btnEdit");
editButton.Enabled = false;
Button deleteButton = (Button)row.FindControl("btnDelete");
deleteButton.Enabled = false;
}
else
{
Button deleteButton = (Button)row.FindControl("btnDelete");
deleteButton.Text = "Cancel";
e.CommandName = "Cancel"; --- This is not possible...what should I do so that the Command Name is changed to Cancel and it does the cancel operation.
}
} }
}
Please help me to get it working…..
The approach you are taking will work fine. However the CommandArgument which is set in your markup
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'is not a reference to the Button itsself but the index of the GridView row the Button resides in.You will need to retrieve the index from the CommandArgument in the RowCommand event and then enable/disable all buttons on other rows like so:
Edit (based on comment)
Try moving the code that modifies the delete button to the RowEditing event handler like so:
Hope this helps.