【问题标题】:how to pass listview row data into another existing form如何将listview行数据传递到另一个现有表单
【发布时间】:2014-01-03 08:32:06
【问题描述】:

我想要 2 个表单,其中第一个表单有一个按钮,可以在对话框表单中加载 form2。 form2 将显示一个显示学生数据的列表视图。现在我需要提取所选行的第一个索引。一旦我双击该行,form2 将关闭并将数据传递到 form1 中的文本框。

我使用下面的代码关闭了我的 form1 并在 form2 中创建了一个新的 form1 实例。

来自form2:

 private void listView1_DoubleClick(object sender, EventArgs e)
 {
  var cl = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
  Form1 wa= new Form1();
  wa.loadid(cl);
  wa.Show();
  this.Close();
 }

来自表格1:

 private void btnReq_Click(object sender, EventArgs e)
 {
        Form2 f2= new Form2();
        f2.Show();
        this.Close();
 }
 public void loadid(String ms)
 {
  String newstring = ms;
  studentid.Text = newstring;
 }

【问题讨论】:

    标签: c# winforms listview


    【解决方案1】:

    我建议使用 Dialog,它会非常简单:

    这是 Form1。您将 f2 实例化并打开为 Dialog,然后等待其结果。OK

    private void Button1_Click(System.Object sender, System.EventArgs e)
    {
        var f2 = new Form2();
    
        if (f2.ShowDialog() == DialogResult.OK) {
            studentId.Text = f2.SelectedStudentId;
        } else {
            studentId.Text = "Select a Student!!!!";
        }
    }
    

    这在 Form2 中,您在其中创建了列表视图和要公开的公共属性:

     public string SelectedStudentId { get; set; }
    
     private void listView1_DoubleClick(object sender, EventArgs e)
     {
        var cl = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
        SelectedStudentId = cl;
        DialogResult = DialogResult.OK; //will close this dialog (form2)
     }
    

    【讨论】:

      【解决方案2】:

      这应该适合你

      在 Form1 中创建一个这样的公共变量:

      public partial class Form1: Form
      {
          //New variable
          public static string StudentIDVal;
      

      然后,将Form1上的点击按钮改为:

      private void btnReq_Click(object sender, EventArgs e)
      {
          Form2 f2= new Form2();
          f2.ShowDialog(); 
          studentid.Text = StudentIDVal;
      }
      

      然后,在 Form2 上点击 item 就可以了:

      private void listView1_DoubleClick(object sender, EventArgs e)
      {
         var cl = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
         Form1.StudentIDVal = cl.ToString();
         this.Close();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-25
        • 2017-01-20
        • 1970-01-01
        • 2016-03-11
        • 2015-12-26
        • 1970-01-01
        • 2013-01-19
        相关资源
        最近更新 更多