Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My Code:
C#
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;
        }


In My Main_Form Code:
C#
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; }
        }
    }

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.
Posted
Updated 24-Jun-16 5:30am
v2

Wrong:
Form2 object_EventList = new Form2();

Right:
Form2 object_EventList = new Form2(this);
 
Share this answer
 
Comments
Member 10261487 24-Jun-16 11:20am    
Thank you, Brother. Its working now. Can you suggest me how can I add rows in DataGridView from Different Froms DataGridView Selected Rows ?
[no name] 24-Jun-16 11:26am    
Just pass the data from selected rows to other form.datagridview. The best way is to copy the data from datatable and pass it to datatable in other form.
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
 
Share this answer
 
Comments
Member 10261487 25-Jun-16 8:25am    
Thank you.
Sergey Alexandrovich Kryukov 25-Jun-16 9:40am    
You are very welcome.
—SA
It's fairly simple: you only set the Form1 instance mainform in your parameterised constructor:
C#
public Form2(Form callingForm)
{
    mainForm = callingForm as Form1;
    InitializeComponent();
}
But when you create the instance of Form2:
C#
Form2 object_EventList = new Form2();

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:
C#
Form2 object_EventList = new Form2(this);


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!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900