c# Winform Controls to VSTO Excel Addin 如何取回值(value)。

标签 c# winforms vsto excel-addins

我是 VSTO Excel Addin 的新手,我希望将 Winform Control 添加到 VSTO 项目。目前我的插件有一个功能区和一个按钮。单击按钮将打开一个 Windows 窗体,其中有几个复选框和一个“完成”按钮。一旦用户点击“完成”,我想捕获用户选择的所有复选框。

这就是我的丝带的样子:

enter image description here

“拆分数据”是按钮,单击它甚至会启动一个 Winform,如下所示:

private void btnSpltData_Click(object sender, RibbonControlEventArgs e)
        {
            FieldSelector fs = new FieldSelector();
            fs.ShowDialog();
        }

enter image description here

使用“完成”按钮,我将关闭表单。我可以使用 checkbox.checked 属性找出选中了哪个复选框,但我不确定如何将其发送回功能区中的 btnSpltData_Click 方法。

我怎样才能做到这一点?有什么指针吗?

private void buttonDone_Click(object sender, EventArgs e)
        {
            this.Close();
        }

最佳答案

您已经通过调用 .ShowDialog(); 显示了表单,很好,这将破坏该行的代码,直到表单关闭。因此,只需将一个属性添加到您的表单中即可稍后读取。 小例子:

public class Ribbon
{
    private void btnSpltData_Click(object sender, RibbonControlEventArgs e)
    {
        FieldSelector fs = new FieldSelector();
        fs.ShowDialog();
        if (fs.DialogResult == DialogResult.OK) // Did user press the 'done' button? or did they exit using X
        {
            foreach (var checkedField in fs.CheckedFields)
            {
                // do stuff with the value
            }
        }
    }
}
public class FieldSelector :  Form
{
    // A property to read after the form has closed
    public List<string> CheckedFields 
    { 
         get; 
    } = new List<string>(); // Never null

    private void buttonDone_Click(object sender, EventArgs e)
    {
        // Retrieve all the Checkboxes that are a direct child of the form
        foreach (var control in Controls.OfType<CheckBox>())
        {
            if (control.Checked)
                CheckedFields.Add(control.Text); // Keep track of the Text value of the checked checkboxes
        }

        this.DialogResult = DialogResult.OK; // just for being neat when using ShowDialog()
        this.Close();
    }
}

关于c# Winform Controls to VSTO Excel Addin 如何取回值(value)。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51542368/

相关文章:

c# - 在 c# (Vsto) 的 Excel 2007 中保存 Excel 模板 2003 时出现问题

c# - 应用程序开始崩溃

c# - 是否可以在运行时在不同的 Winform 项目上使用不同的配置文件?

vb.net - 如何更改winform中文本框的边框颜色和宽度?

c# - 另存为

visual-studio-2012 - 可用于VSTO开发的最低Office 2013版本是多少?

c# - VSTO问题-无法创建Visual Studio Excel工作簿项目

c# - 在 VS 调试器中获取方法的返回值

c# - 使用数据注释的多对多映射

c# - Task.Factory.StartNew() 重载