Get-Set在按钮访问时返回null

时间:2014-03-23 05:46:00

标签: c# button get set

我可能错过了一些简单的东西,但是已经搞乱了几个小时,我无法让方法返回非空的东西。当我踩过这个过程时,getDir1将获取类" swSheetFormatCycle.Form1.FolderUpdate"的值,但是getDir1.SwDir保持为null,因此swDir保持为null。按钮方法是不是按照我的方式设置swDir或swTemplate?

   // Get-Set Class
public class FolderUpdate
{
    private string swDir;
    public string SwDir
    {
        get {return swDir;}
        set {swDir = value;}
    }

    private string swTemplate;
    public string SwTemplate
    {
        get {return swTemplate;}
        set {swTemplate = value;}
    }
}

private void btnTemBrow_Click(object sender, EventArgs e)
{
    OpenFileDialog tempBrowse = new OpenFileDialog();
    DialogResult result = tempBrowse.ShowDialog();
    string tempText = tempBrowse.FileName;
    txtTemp.Text = tempText;
    // Setting the template field
    FolderUpdate temUpd = new FolderUpdate();
    temUpd.SwTemplate = tempText;
}

private void btnDirBrow_Click(object sender, EventArgs e)
{
    FolderBrowserDialog dirBrowse = new FolderBrowserDialog();
    DialogResult result = dirBrowse.ShowDialog();
    string dirText = dirBrowse.SelectedPath;
    txtDir.Text = dirText;
    // Setting the directory field
    FolderUpdate dirUpd = new FolderUpdate();
    dirUpd.SwDir = dirText;
}

// Get the directory set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir1 = new swSheetFormatCycle.Form1.FolderUpdate();
string swDir = getDir1.SwDir;

// Get the template set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir2 = new swSheetFormatCycle.Form1.FolderUpdate();
string swTemplate = getDir2.SwTemplate;

1 个答案:

答案 0 :(得分:0)

您的按钮事件正在创建FolderUpdate类的新实例,然后没有对该对象执行任何操作,并且在方法调用结束时将其放弃。

你的" //获取按钮方法设置的目录"码 也正在创建实例,因此它们也将为空

将FolderUpdate实例附加到表单本身,以便您可以引用它。

public class FolderUpdate
{
    .... 
}


public FolderUpdate Folders { get; set; }

private void btnTemBrow_Click(object sender, EventArgs e)
{
     ...
     Folders.SwTemplate = tempText;
}

private void btnDirBrow_Click(object sender, EventArgs e)
{
     ...
     Folders.SwDir = dirText;
}


// Then when you are reading them
var folders = swSheetFormatCycle.Form1.Folders;
string swDir = folders.SwDir;
string swTemplate = folders.SwTemplate;