Jonathan Viju Mathai Jonathan Viju Mathai - 8 days ago 6
C# Question

C# WinForm how to link a command to a dynamically made checkbox?

I am currently making a flash drive lock (it hides/unhides folders) in C# Winform.

I've already ready made it the C# Console, so i have most of the commands needed. I have a dir command getting the paths to the all the folders

public static dynamic getFolder()
{
Dictionary<dynamic, List<dynamic>> dictionary = new Dictionary<dynamic, List<dynamic>>();

int selector = 1;
bool isHidden;
foreach (string folderPath in Directory.GetDirectories(Form2.driveLetter))
{
List<dynamic> data = new List<dynamic>();
string folderName = folderPath.Substring(3);
if (folderName == "#") { continue; }
if (folderName == "System Volume Information") { continue; }
isHidden = Status(folderPath);

data.Add(folderPath.Substring(3, folderPath.Length - 3));
data.Add(isHidden);
data.Add(folderPath);

dictionary.Add(selector, data);
selector++;
}

dictionary.Add(selector++, Vault());
return dictionary;
}
then I have the Dictionary piped into a different method that gets the names of the folder(and hidden state) then turns them into checked boxes; if the folder is hidden, then the box is checked, and if it isn't, then its unhidden (I will in time make this part more efficient)


then I have the Dictionary piped into a different method that gets the names of the folder (and hidden state) then turns them into checked boxes; if the folder is hidden, then the box is checked, and if it isn't, then its unhidden (I will in time make this part more efficient)

private void CreateBox(Dictionary<dynamic, List<dynamic>> dictionary)
{
int y = 0;
int z = 0;
CheckBox box;
for (int x = 1; x < dictionary.Count(); x++)
{
List<dynamic> folder = dictionary[x];
box = new CheckBox();
box.Text = folder[0];
box.AutoSize = true;
box.Checked = folder[1];

if (y == 180)
{
box.Location = new Point(370, 39 + z);
z += 20;
}
else
{
box.Location = new Point(198, 39 + y);
y += 20;
}
this.Controls.Add(box);
CheckBoxes.Add(box);
}
}


image #1

image #2

How do I link a SetAttributes command to the check box, so when the box is checked, it hides the respective folder and when the box is unchecked, it unhides the folder

Answer

All you need to do is to hook the event when you're creating your checkBoxes.

private void CreateBox(Dictionary<dynamic, List<dynamic>> dictionary)
{
    int y = 0;
    int z = 0;
    CheckBox box;
    for (int x = 1; x < dictionary.Count(); x++)
    {
        List<dynamic> folder = dictionary[x];
        box = new CheckBox();
        box.CheckedChanged += box_CheckedChanged; // here
        box.Text = folder[0];
        box.AutoSize = true;
        box.Checked = folder[1];
        this.Controls.Add(box);
    }
}

private void box_CheckChanged(object sender, EventArgs e)
{
    // some code here.
}
Comments