我如何做某事"什么时候取消SaveFileDialog?

时间:2015-10-09 03:17:59

标签: c# winforms

NB:答案in this question已过期。

所以,我有一个保存对话框:

function GetItems() {
    var names = [];
    $().SPServices({
        operation: "GetListItems",
        async: true,
        listName: "GatheredSites",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
        CAMLQuery: "<Query><OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy></Query>",
        completefunc: function (xData, Status) {
            if (Status == 'success') {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
                    var name = ($(this).attr("ows_Title"));
                    names.push(name);
                });
                $().SPServices({
                    operation: "GetWebCollection",
                    webURL: "*url*",
                    async: true,
                    completefunc: function (xData, Status) {
                        $(xData.responseXML).find("Webs > Web").each(function () {
                            var $node = $(this);
                            names.push($node.attr("Title"));
                        });
                        names.sort();
                        var output = $("#divItems");
                        for (var i = 0, len = names.length; i < len; i++) {
                            output.append("<li>" + names[i] + "</li>");
                        }
                    }
                });
            } else {
                jQuery("#displayItems").append("<div>Empty</div>");
            }    
        }
    });
}

但...... ... SaveFileDialog sfd = new SaveFileDialog(); sfd.ShowDialog(); // SaveFileDialog.[Whatever] - Init code basically. if (sfd.DialogResult == DialogResult.OK) { // Definitely do something. Console.Print("File selected."); } if (sfd.DialogResult == DialogResult.Abort) { // Maybe the opposite of the above? Console.Print("File selection Cancelled"); } if ( ... ) { } and so on. 已被事件取代......

唯一可用的事件是SaveFileDialog.DialogResultSaveFileDialog.FileOKSaveFileDialog.Disposed

如何在用户点击取消而非完成时触发事件(或转移到一行代码)(点击保存)?

我希望根据用户是取消还是成功选择要保存的文件位置进行分支。

1 个答案:

答案 0 :(得分:5)

不推荐使用DialogResult,这些事件也不是新事物 要执行取消操作,您可以创建SaveFileDialog并对其进行配置,然后拨打ShowDialog,然后检查结果:

var sfd= new SaveFileDialog();
//Other initializations ...
//sfd.Filter= "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//sfd.DefaultExt = "txt";

if(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    MessageBox.Show("Save Clicked");
    //ِDo something for save
}
else
{
    MessageBox.Show("Cancel Clicked");
    //Do something for cancel
}

您可以使用FileName属性访问所选文件,例如MessageBox.Show(sfd.FileName);