c#根据按钮单击删除动态创建的复选框

时间:2014-10-20 15:28:26

标签: c# winforms streamreader

我迷路了。我想从文本文件中删除一个值。该值为checkbox.Name。我想打开一个文本文件,在文本文件中找到相应的用户名,删除它并根据按钮单击保存文件。

以下是我获取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();

}

我可以根据点击事件访问checkbox.Name,所以我知道我收到了正确的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
    {

    }


}

我一直在寻找这个早上和周五的一整天。任何人都可以指出我正确的方向或可能建议一些示例代码。请拜托。先感谢您。我真的很感激。 :-D

1 个答案:

答案 0 :(得分:1)

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);
}