如何将Datagridview值发送到主窗体

时间:2018-03-08 09:46:36

标签: c# winforms datagridview

我想将我的Datagridview值发送到我的mainform中的Combobox。

这是我的Datagridview表单中的代码:

private void EquipmentList_Load(object sender, EventArgs e)
{
    DataTable.RowCount = 30;

    //Beam Description default value
    DataTable.Rows[0].Cells[1].Value = "8.000m x 0.400m x 0.550m";
}

以下代码是我使用但未发生的事情:

        private void MainForm_Load(object sender, EventArgs e)
    {
        this.KeyPreview = true;


        EquipmentList ELform = new EquipmentList();

        //Beam Combo Box default values
        var BCBi1 = ELform.DataTable.Rows[0].Cells[1].Value.ToString();


        this.BeamCB.Items.Add(BCBi1);


    }

当我运行它时,我收到此错误:

error when running

预先感谢所有帮助我的人。

2 个答案:

答案 0 :(得分:1)

DataTable.Rows[0].Cells[1].Value在加载时以EquipmentList形式分配。

EquipmentList ELform = new EquipmentList(); - 此处已创建但尚未加载(您需要为此调用ShowShowDialog)。

我建议声明可公开访问的默认值(并且不依赖于DataTable对象存在1行,这是一个低级实现细节)

public const string DefaultSize = "8.000m x 0.400m x 0.550m";

private void EquipmentList_Load(object sender, EventArgs e)
{
    DataTable.RowCount = 30;

    DataTable.Rows[0].Cells[1].Value = DefaultSize;
}

然后

private void MainForm_Load(object sender, EventArgs e)
{
    this.KeyPreview = true;

    this.BeamCB.Items.Add(EquipmentList.DefaultSize);
}

答案 1 :(得分:0)

问题"所以有没有可能在没有点击/显示我的设备清单表格的情况下加载这些值。"绝对。首先为您的数据构建public class Program { static void Main(string[] args) { Console.WriteLine("Please enter any value"); string str = Console.ReadLine(); ThreadStart childref = new ThreadStart(CallToChildThread); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadLine(); } public static void CallToChildThread() { Console.WriteLine("Child thread starts"); // the thread is paused for 5000 milliseconds int sleepfor = 5000; Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000); Thread.Sleep(sleepfor); Console.WriteLine("Child thread resumes"); } }

class

添加中介类:

public class gridviewdata
{
   public string content { get; set; }
   public int row { get; set; }
   public int cell { get; set; }

   public gridviewdata(string content, int row, int cell)
   {
       this.content = content;
       this.row = row;
       this.cell = cell;
   }
}

然后将此代码添加到您的public static class mediator { public static List<gridviewdata> gridviewdatalist; } 加载事件中:

ELform

然后添加一种新方法,将您的特定private void EquipmentList_Load(object sender, EventArgs e) { DataTable.RowCount = 30; //Beam Description default value DataTable.Rows[0].Cells[1].Value = "8.000m x 0.400m x 0.550m"; mediator.gridviewdatalist.Add(new gridviewdata("8.000m x 0.400m x 0.550m", 0, 1); } 标识为row

MainForm

最后在private gridviewdata selectdata(int row, int cell) { foreach(gridviewdata data in mediator.gridviewdatalist) { if(data.row == row && data.cell == cell) { return data; } } return null; }

中调用该代码
MainForm

希望这有帮助。