user3001977
user3001977

Reputation:

how to compare two dgv and pass datagridview to another Form c#

I have two datagridview that each contain two columns and the same numbers of rows.I compared these two datagridview using this loop :

 int result = 0;
 for (int i=0;i< dgvInvent1.RowCount;i++)
 {
   var src1 = dgvInvent1.Rows[i].Cells[1].Value.ToString();
   var src2 = dgvInvent2.Rows[i].Cells[1].Value.ToString();
   result = Int32.Parse(src1) - Int32.Parse(src2);
 }

I want to transfer the result to another datagridview too, I named it "dgvFinal" , except that dvgFinal is in another form called "Form2" that I just created , so i added this line to form2

public DataGridView dvgFinal { get; set; }

and in my main Form i added to my loop

Form2 re = new Form2();
            int result = 0;
            for (int i=0;i< dgvInvent1.RowCount;i++)
            {
                var src1 = dgvInvent1.Rows[i].Cells[1].Value.ToString();
                var src2 = dgvInvent2.Rows[i].Cells[1].Value.ToString();
                 result = Int32.Parse(src1) - Int32.Parse(src2);
                re.dvgFinal.Rows[i].Cells[2].Value = result;
            }

but it doesn't work , i get

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.

someone could help me ? Thank you in advance

Upvotes: 1

Views: 198

Answers (3)

er-sho
er-sho

Reputation: 9771

1) Use DataTable to load all your results like.

Form5 re = new Form5();
int result = 0;
DataTable dt = new DataTable();
dt.Columns.Add("Result");

for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
    DataRow row = dt.NewRow();
    var src1 = dataGridView1.Rows[i].Cells[0].Value;
    var src2 = dataGridView2.Rows[i].Cells[0].Value;
    result = Convert.ToInt32(src1) - Convert.ToInt32(src2);

    row["Result"] = result;
    dt.Rows.Add(row);

}

re.DataTable = dt;
re.Show();

2) Create a new public property of DataTable on target form so we can access it from our source form like

public DataTable DataTable { get; set; }

3) Add one DataGridView from toolbox or from code to target form like dgvFinal.

If you want to manually add column to your dgvFinal then set it ColumnType to DataGridViewTextBoxColumn and DataPropertyName to Result from property window.

4) Add Form_Load method to your target form and assign DataSource

private void Form5_Load(object sender, EventArgs e)
{
    this.dgvFinal.DataSource = DataTable;
}

Output:

Source Form

enter image description here

Target Form

enter image description here

Edit:

If you want to set custome header name for each of your column in datagridview then set HeaderText value.

In this case the datagridview is your dgvFinal

Select datagridview => open property window => choose columns property => choose your desired column => choose and set HeaderText value.

If you want to add more columns in your dgvFinal then you can add repective columns in your datatable in point no 1 listed above like

dt.Columns.Add("Result1");
dt.Columns.Add("Result2");
dt.Columns.Add("Result3");

And in for loop you can assign rows value to each of your column like

result1 = Convert.ToInt32(src1) - Convert.ToInt32(src2);
result2 = Convert.ToInt32(src1) + Convert.ToInt32(src2);
result3 = Convert.ToInt32(src1) * Convert.ToInt32(src2);

row["Result1"] = result1;
row["Result2"] = result2;
row["Result3"] = result3;  

You may assign any values to each of your row, it may be from your dgvInvent1 or from dgvInvent2 or any of your calculated values.

And finally set HeaderText values for each of your above column in dgvFinal

Upvotes: 1

Cetin Basoz
Cetin Basoz

Reputation: 23837

Here is a full working sample:

void Main()
{
    DataTable tbl1 = new DataTable();
    DataTable tbl2 = new DataTable();

    using (SqlConnection con = new SqlConnection(@"server=.\SQLExpress;Database=Test;Trusted_Connection=yes"))
    {
        string query = @"with myTally (N) as (
             select top(10) row_number() over (order by t1.object_id)
             from sys.all_columns t1 
             cross join sys.all_columns t2)
             select cast(N * 1000 * rand() as int) as col1, cast(N * 100 * rand() as int) as col2
             from myTally";
             con.Open();
        tbl1.Load(new SqlCommand(query, con).ExecuteReader());
        tbl2.Load(new SqlCommand(query, con).ExecuteReader());
    }

    Form f1 = new Form();
    var dgv1 = new DataGridView { Top = 10, Left = 10, Height = 100, DataSource = tbl1 };
    var dgv2 = new DataGridView { Top = 130, Left = 10, Height = 100, DataSource = tbl2 };
    var btn = new Button {Top=250, Left=10, Text="Show 3rd Grid"};

    f1.Controls.AddRange(new Control[] {dgv1, dgv2, btn});

    btn.Click += (sender, args) =>
    {
        DataTable tbl3 = new DataTable();
        tbl3.Columns.Add("Result", typeof(int));
        for (int i = 0; i < tbl1.Rows.Count; i++)
        {
            tbl3.Rows.Add((int)tbl1.Rows[i]["col1"] - (int)tbl2.Rows[i]["col1"]);
        }

        Form f2 = new Form();
        var dgv3 = new DataGridView {Dock=DockStyle.Fill, DataSource=tbl3};
        f2.Controls.Add(dgv3);
        f2.ShowDialog();
    };

    f1.Show();
}

Upvotes: 0

Viggo Lund&#233;n
Viggo Lund&#233;n

Reputation: 798

Form2 re = new Form2();
int result = 0;
for (int i=0 ;i< dgvInvent1.RowCount; i++)
{
    var src1 = (int)dgvInvent1.Rows[i].Cells[1].Value;
    var src2 = (int)dgvInvent2.Rows[i].Cells[1].Value;
    result = src1 - src2;
    re.dvgFinal.Rows.Add(result.ToString());
}

This should work for you. The reason is that you try to access rows that aren't there yet.

However, consider using Datasource instead.

Upvotes: 1

Related Questions