我有两个组合框(表单 1 中的组合框 1 和表单 2 中的组合框 2)。 我需要导入一个 excel 文件,并且 combobox1 获取工作表名称。 然后在 form2 中(我不想再次导入同一个文件)我有 combobox2,它也有来自 combobox1 的相同工作表名称。
我试过了,但我得到了 NULLFUNCTION 表达式的错误(附加信息:对象引用没有设置为对象的实例)。
using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Excel 97-2003 Workbook|*.xls|Excel Workbook|*.xlsx |fichiers Textes (*.txt)|*.txt|fichiers CSV (*.csv)|*.csv|tous les fichiers (*.*)|*.*" })
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
TextBox_Emplacement.Text = openFileDialog.FileName;
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
});
dataTableCollection = result.Tables;
dataTableCollection1 = result.Tables;
sheet.Items.Clear();
//cp.radDropDownList1.Items.Clear();
foreach (DataTable table in dataTableCollection)
sheet.Items.Add(table.TableName);//add sheet to combobox
**Form_Copie cp1 = (Form_Copie)Application.OpenForms["Form_Copie"];
foreach (DataTable table in dataTableCollection)
cp1.radDropDownList1.Items.Add(table.TableName);//add sheet to combobox**
答案 0 :(得分:0)
有几种方法可以做到这一点。重载构造函数是一个好方法,但是对每个控件执行此操作会很快变得令人生畏和混乱。如果您想为多个控件执行此操作,我建议使用包含绑定属性(例如 System.ComponentModel.BindingList 和/或 System.Forms.Binding)作为每个表单中的字段的模型。然后重载构造函数并通过模型类传入绑定。
public class BindingModel {
public property BindingList<string> ComboBoxBinding {get;set;}
... other binding/non-binding properties ...
}
public class Form1{
private BindingModel _bindingModel = new _bindingModel();
private void Form1_Shown(object sender, EventArgs e) {
this.ComboBox1.DataSource = _bindingModel.ComboBoxBinding;
this.ComboBox1.DataMember = "";
// the add would go in your excel method
_bindingModel.ComboBoxBinding.Add("Item 1");
}
private void btnOpenForm2_Click(object sender, EventArgs e) {
var frm = new Form2(_bindingModel);
frm.Show();
this.Close();
}
}
public class Form2{
private BindingModel _bindingModel = new _bindingModel();
public void Form2(BindingModel bindingModel){
this._bindingModel = bindingModel;
}
// Once the form is shown bind the ComboBox and it will populate the values
private void Form2_Shown(object sender, EventArgs e){
this.ComboBox1.DataSource = _bindingModel.ComboBoxBinding;
this.ComboBox1.DataMember = "";
}
}
或者,可以在调用表单中设置控件项:
public class Form1{
private void btnOpenForm2_Click(object sender, EventArgs e) {
var frm = new Form2();
for(int i = 0; i < this.ComboBox1.Count - 1; i++){
frm.ComboBox1.Items.Add(ComboBox1.Items[i]);
}
frm.Show();
this.Close();
}
}