Search code examples
c#winformsstreamreader

c# Remove a dynamically created checkbox based on a button click


I'm lost. I want to remove a value from a text file. The value is a checkbox.Name. I want to open a text file, find the corresponding username in the textfile, remove it and save the file based on a button click.

Here is how I get the checkbox.Name

public static void getPermText(System.Windows.Forms.Form targetForm)
{
    Stream fileStream = File.Open(dataFolder + PermFile, FileMode.Open);
    StreamReader reader = new StreamReader(fileStream);

    string line = null;

    line = reader.ReadToEnd();


    string[] parts = line.Split('\n');

    string user = userNameOnly();
    try
    {

        int userCount;

        userCount = parts.Length;

        CheckBox[] chkPerm = new CheckBox[userCount];
        int height = 1;
        int padding = 10;

        for (int i = 0; i < userCount; i++)
        {
            chkPerm[i] = new CheckBox();

            string Perm = "Perm";

            chkPerm[i].Name = parts[i].Trim('\r') + Perm;

            chkPerm[i].Text = parts[i];

            chkPerm[i].TabIndex = i;

            chkPerm[i].AutoCheck = true;

            chkPerm[i].Bounds = new Rectangle(15, 40 + padding + height, 100, 22);

            //Assigns an eventHandler to the chkPerm.CheckBox that tells you if something is clicked, then that checkBox is selected/checked.
            //Not currently in use.
            chkPerm[i].Click += new EventHandler(checkChangedPerm);


            targetForm.Controls.Add(chkPerm[i]);

            height += 22;

            //MessageBox.Show(chkPerm[i].Name);

        }



    }
    catch
    {

    }
    fileStream.Close();

}

I can access the checkbox.Name based on a click event so I know I'm getting the correct checkbox.Name

public static void checkChangedPerm(Object sender, EventArgs e)
{

    CheckBox c = sender as CheckBox;

    if (c.Name != null && c.Name != "")
    {
        int count = c.Name.Count();

        string trimmed = c.Name.ToString();
        string outPut = trimmed.Remove(count - 4);


    }
    else
    {

    }


}

I've been searching for this most of the morning and all day Friday. Can anyone point me in the right direction or possibly suggest some sample code. Please Please. Thank you in advance. I truly do appreciate it. :-D


Solution

  • StreamReader reader;
    StreamWriter writer;
    
    string line, newText = null;
    
    using (reader = new StreamReader(@"..."))
    {
        while ((line = reader.ReadLine()) != null)
        {
            if (line != "checkbox name")
            {
                newText += line + "\r\n";
            }
        }
    }
    
    newText = newText.Remove(newText.Length - 2); //trim the last \r\n
    
    using (writer = new StreamWriter(@"...")) //same file
    {
        writer.Write(newText);
    }