【问题标题】:Double click row in datagridview and get value of specific cell and pass it to another form双击datagridview中的行并获取特定单元格的值并将其传递给另一个表单
【发布时间】:2018-09-14 14:52:12
【问题描述】:

我只是想知道下面的情况是否正确

我正在尝试以下 1-从MyDataGridView1中的Form1双击MyDataGridView1行我正在获取特定列的值并将其传递给FORM2

2- 将该值分配给 Form2 上的 Textbox

datagridview获取ti ID的事件下方

private void MyDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
       vID = MyDataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

       this.Close();
       Form2 NewForm = new Form2();
       NewForm.Show();
    }

然后将值保存到

public static string vID ;

没有Form2

Textboxid.Text = F0103.vID ;

在下面的行中,我正在尝试为textbox 的休假活动提供午餐,但它不起作用是否有任何午餐休假活动的想法

BTN_Refresh.Focus(); 

【问题讨论】:

  • 假设vID 正确获取对象,您应该在Form2 的构造函数中添加代表该数据类型的重载。然后像Form2 NewForm = new Form2(vID); 一样传递它。在传递参数之后,this.Close() 也可能会更好。
  • @DavidBentley 请介意用示例发布答案

标签: c# winforms .net-4.0


【解决方案1】:

完整答案:

表格1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        List<Stuff> stuff = new List<Stuff>();
        stuff.Add(new Stuff() { Foo = "Foo1", Bar = "Bar1", Data = "Data1" });
        stuff.Add(new Stuff() { Foo = "Foo2", Bar = "Bar2", Data = "Data2" });

        var bindingList = new BindingList<Stuff>(stuff);
        var source = new BindingSource(bindingList, null);
        dataGridView1.DataSource = source;
    }

    private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        string arg = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

        Form2 form2 = new Form2(arg);
        form2.Show();

        this.Hide();
    }
}

public class Stuff
{
    public string Foo { get; set; }
    public string Bar { get; set; }
    public string Data { get; set; }
}

表格2:

public partial class Form2 : Form
{
    public Form2(string arg)
    {
        InitializeComponent();

        label1.Text = arg;
    }
}

关于 winforms(以及为什么我改用 WPF)的一件事是它过于复杂了。根据我的测试,this.Close() 关闭了整个应用程序,我不得不改用this.Hide()

另外,养成传递参数而不是设置全局变量的习惯是件好事。 C# 中的几乎所有内容都可以以某种方式作为参数传递,这使得代码更好、更简洁。

【讨论】:

  • 谢谢,我会试一试,但在处理分配给textbox 上的“文本框”的值之后的最后一件事是leave 事件如何午餐该事件?
  • vID 可以为空吗? Form2 NewForm = new Form2(vID); 因为我并不总是会传递这个值,有时这个值可能是 null
【解决方案2】:

如果我正确理解了您的问题。您可以将字符串传递给您的 Form2 构造函数。

private void MyDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
  vID = MyDataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

  Form2 NewForm = new Form2(vID);

  this.Close();

  NewForm.Show();
}

然后在构造函数中,将TextBox文本设置为这个字符串。

public class Form2
{
  public Form2(string vid)
  {
    InitializeComponent();

    Textboxid.Text = vid;
  }
}

【讨论】:

  • vID 可以为空吗? Form2 NewForm = new Form2(vID); 因为我并不总是会传递这个值,有时这个值可能是 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多