如何在datagridview中添加来自不同表单的datagridview的行 [英] How to add rows in datagridview from different form's datagridview

查看:84
本文介绍了如何在datagridview中添加来自不同表单的datagridview的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

My Code:

private Form1 mainForm = null;
        public Form2(Form callingForm)
        {
            mainForm = callingForm as Form1;
            InitializeComponent();
        }

 private void btnAddEvent_Click(object sender, EventArgs e)
        {
            int count = 1;
            DataTable dt = new DataTable();
            dt.Columns.Add("Sl", typeof(string));
            dt.Columns.Add("Device", typeof(string));
            dt.Columns.Add("Event Name", typeof(string));
            dt.Columns.Add("frame", typeof(string));
            dt.Columns.Add("frame_rate", typeof(string));
            dt.Columns.Add("event_duration", typeof(string));



            foreach (DataGridViewRow row in dtgrid_event_list.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                dt.Rows.Add();
                if (chk.Value.ToString() == "True")
                {

                    
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        int j = 0;
                        
                            dt.Rows[row.Index][j] = cell.Value.ToString();
                        j++;
                    }


                }
                

            }

            this.mainForm.DataGrid_Data = dt;
        }





在我的Main_Form代码中:



In My Main_Form Code:

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

        private void btn_AddEvents_Click(object sender, EventArgs e)
        {
            Form2 object_EventList = new Form2();
            object_EventList.Show();

        }

        public DataTable DataGrid_Data
        {
            
            set { dataGridView1.DataSource = value; }
        }
    }



现在我想从另一个表单设置dataGridView1.DataSource。



我尝试过:



在我的Main_Form中我有代码。

public DataTable DataGrid_Data

{



set {dataGridView1.DataSource = value; }

}

和另一个我称之为Main_Form的表格如下:



private Form1 mainForm = null;

public Form2(Form callingForm)

{

mainForm = callingForm as Form1;

InitializeComponent() ;

}



现在排队异常:this.mainForm.DataGrid_Data = dt;

请帮忙我从另一个Form的DataGridView的选定行中添加DataGridView中的行。

提前谢谢。


Now I want to set dataGridView1.DataSource from another Form.

What I have tried:

In my Main_Form I have Code.
public DataTable DataGrid_Data
{

set { dataGridView1.DataSource = value; }
}
And the another Form I have call Main_Form as Like this:

private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}

Now getting Exception in line: this.mainForm.DataGrid_Data = dt;
Please help me to Add Rows in DataGridView from another Form's DataGridView's selected Rows.
Thank you in advance.

推荐答案

错误:

Wrong:
Form2 object_EventList = new Form2();



右:


Right:

Form2 object_EventList = new Form2(this);


您只需要在调试器下检查此行发生了什么。在 this.mainForm.DataGrid_Data 中, this.mainForm 在执行时可能为null(如果它不为null但是 this.mainForm.DataGrid_Data 为空,没关系,因为该语句是赋值)。然后你解除引用 this.mainForm 对其成员进行寻址,并获得此异常。



你真的需要学会自己处理这些案件;每次碰巧都不能问这些问题。



不用担心。这是最容易检测和修复的案例之一。它只是意味着某些引用类型的某个成员/变量通过使用及其实例(非静态)成员进行解引用,这需要此成员/变量为非null,但实际上它似乎为null。只需在调试器下执行它,它将停止抛出异常的执行。在该行上设置一个断点,重新启动应用程序并再次到达这一点。评估下一行中涉及的所有引用,并查看哪一个为null,而不需要为null。解决这个问题之后,修复代码:要么确保将成员/变量正确初始化为非空引用,要么将其检查为null,如果为null,则执行其他操作。



另请参阅:想要在按钮点击时显示下一条记录。但是如果下一个记录功能的条件对象引用未设置为对象的实例则会出错。



有时候,你不能这样做在调试器下,由一个或另一个原因。一个非常讨厌的情况是,只有在调试信息不​​可用时构建软件时才会出现问题。在这种情况下,你必须使用更难的方式。首先,你需要确保你永远不会通过静默处理异常来阻止异常的传播(这是开发人员对自己的犯罪,但很常见)。您需要在每个线程的最顶层堆栈帧上捕获绝对所有异常。如果处理类型 System.Exception 的异常,则可以执行此操作。在处理程序中,您需要记录所有异常信息,尤其是 System.Exception.StackTrace

http://msdn.microsoft.com/en-us/library/system.exception.aspx

http://msdn.microsoft.com/en-us/library/ system.exception.stacktrace.aspx



堆栈跟踪只是一个字符串,显示从throw语句到处理程序的异常传播的完整路径。通过阅读,您总能找到目的。对于日志记录,使用类 System.Diagnostics.EventLog

http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx






现在,以草率的方式组织表单之间的协作并不好:直接将表单成员彼此暴露,直接使用字段。这是你的bug来自哪里,根本原因。这是一个常见的问题,所以我写了一篇关于这个主题的文章。请参阅: 一次回答的许多问题 - Windows窗体之间的协作或WPF Windows



祝你好运,

-SA
You just need to inspect under the debugger what happens on this line. In this.mainForm.DataGrid_Data, this.mainForm could be null at the moment of execution (if it is not null but this.mainForm.DataGrid_Data is null, it does not matter, because the statement is the assignment). Then you dereference this.mainForm be addressing to its member, and get this exception.

You really need to learn dealing with such cases by yourself; you cannot ask such questions every time it happens.

Not to worry. This is one of the easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferences by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.



Now, it's not good to organize collaboration between forms in such as sloppy manner: directly exposing form members to each other, using fields directly. This is where your bug comes from, the root cause. This turned out to be a common problem, so I wrote an article on the topic. Please see: Many Questions Answered at Once — Collaboration between Windows Forms or WPF Windows.

Good luck,
—SA


这很简单:你只在参数化构造函数中设置Form1实例 mainform

It's fairly simple: you only set the Form1 instance mainform in your parameterised constructor:
public Form2(Form callingForm)
{
    mainForm = callingForm as Form1;
    InitializeComponent();
}

但是当你创建Form2的实例时:

But when you create the instance of Form2:

Form2 object_EventList = new Form2();



你调用无参数构造函数。

所以当你尝试使用 mainForm 稍后,它是null,你得到错误。

将Form1实例传递给构造函数,一切都应该很好:


You call the parameterless constructor.
So when you try to use mainForm later, it's null, and you get the error.
Pass the Form1 instance to the constructor, and all should be well:

Form2 object_EventList = new Form2(this);





但你不应该这样做!

相反,Form2不应该根本不了解Form1 - 它违反了OOP的规则,因为这两种形式不是独立的。

相反,你应该在Form2处理Form2中创建一个事件,然后让Form1通过Form2属性获取数据,并从中设置DataSource。

听起来很复杂?是的,它确实!但事实并非如此 - 这很简单。

见这里:在两个表格之间传递信息,第2部分:儿童到父母 [ ^ ]

Form1是Parent,Form2是Child - 它与a无关正式的MDI关系!



But you shouldn't be doing it like that!
Instead, Form2 shouldn't know about Form1 at all - it's against the "rules" of OOPs if it does, because the two forms aren't independant.
Instead, you should create an event in Form2 which Form1 handles, and let Form1 get the data if it wants it via a Form2 property, and set the DataSource from that.
Sounds complicated? Yes, it does! But it isn;t really - it's pretty simple.
See here: Transferring information between two forms, Part 2: Child to Parent[^]
Form1 is the "Parent", Form2 is the "Child" - and it has nothing to do with a formal MDI relationship!


这篇关于如何在datagridview中添加来自不同表单的datagridview的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆