C# WinForm:从列表框中显示的列表中编辑 object

C# WinForm: Editing object from list being displayed in ListBox

我的列表框包含 Object 的一部分(标题和名称,object 包含 4 个字符串)。 当列表框中的项目突出显示时,我希望能够通过 'edit' 按钮以第二种形式编辑 object 。

此列表框由表单 2 上的数据源填充,编辑表单将是表单 3。

这是我的 'edit' 按钮代码:

    private void edit_Click(object sender, EventArgs e)
    {
        object item = listBox1.SelectedItem;
        Form3 MyForm = new Form3();
        MyForm.Owner = this;
        MyForm.Show();
    }

然后如何填充 form3 中的字段并进行编辑? :)

您将项目(在适当的转换之后)传递给 Form3 构造函数或在 Form3 上使用自定义 public 属性 来设置检索的项目

对于这些示例,我假设存储在您的列表框中的每个项目都是一个名为 MyClass 的 class 的实例(用您正确的 class 名称更改它)

正在将项目传递给 Form3 构造函数

private void edit_Click(object sender, EventArgs e)
{
    MyClass item = listBox1.SelectedItem as MyClass;
    if(item != null)
    {
         Form3 MyForm = new Form3(item);
         MyForm.Owner = this;
         MyForm.Show();
    }
}

在 Form3 构造函数中

public class Form3 : Form
{
     MyClass currentItemToEdit = null;
     public Form3(MyClass itemToEdit)
     {
         InitializeComponent();
         currentItemToEdit = itemToEdit;
         txtBoxTitle.Text = currentItemToEdit.Title;
         ......
     }
}

使用自定义 属性

在 Form3 中定义了一个 public 属性

public class Form3 : Form
{
     public MyClass ItemToEdit {get; set;}
     public Form3()
     {
         InitializeComponent();
     }
     protected void Form_Load(object sender, EventArgs e)
     {
         if(this.ItemToEdit != null)
         {
             txtBoxTitle.Text = ItemToEdit.Title;
              ......
         }
     }
}

而在第一种形式中你写

private void edit_Click(object sender, EventArgs e)
{
    MyClass item = listBox1.SelectedItem as MyClass;
    if(item != null)
    {
         Form3 MyForm = new Form3();
         MyForm.Owner = this;
         MyForm.ItemToEdit = item;
         MyForm.Show();
    }
}