'Enabling and Disabling DataGridView button cell
I have made a DataGridView in a Windows Form with the Name serverList
and then added a selection of columns then at the end of each row I have added a button cell using this code
DataGridViewButtonColumn deleteBtn = new DataGridViewButtonColumn();
deleteBtn.HeaderText = "Delete";
deleteBtn.Text = "Delete";
deleteBtn.Name = "deleteBtn";
deleteBtn.UseColumnTextForButtonValue = true;
serverList.Columns.Add(deleteBtn);
is there a way for me to grey this button out or make it so the user can't click it?
EDIT: I check when the button is clicked with this method:
private void serverList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
switch (e.ColumnIndex)
{
case 8:
try
{
string filePath = @"C:\ProgramData\Server_Manager\default.xml";
int serverIndex = Int32.Parse(serverCell);
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlElement nodeToDelete = (XmlElement)doc.SelectSingleNode("/Servers/Server[serverIndex="+serverIndex+"]");
if (nodeToDelete != null)
{
nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
}
doc.Save(filePath);
clearList();
populateList();
}
catch (Exception ex)
{
string errorMsg = "Unable to Delete Nodes from XML: " + ex;
errorBox(errorMsg, "Failed to Delete List Item", "error");
}
break;
Solution 1:[1]
Solution:
Rather than disable the button I instead created an error when the button is clicked:
MessageBox.Show("Server Currently Being Edited by Another User");
Solution 2:[2]
The Property you are looking for should be found under "deleteBtn.Enabled", possible Values are true/false.
You can set this property at any time in your code.
Solution 3:[3]
I went a different route with this as I couldn't find an answer anywhere when using the CellContentClick event.
I used an int List to store e.index when the button was clicked and the process successfully began (from a Y/N message box).
When CellContentClick is entered I first check to see if the row index was in the list and to not show the message box again to begin processing until the process finished. I also disabled the button so it greyed out on the form.
When it the process finishes, the button is enabled again and e.index is removed from the List.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Logan Young |
Solution 2 | kurdy |
Solution 3 | FantaOrangeFanBoy |