-2

I have a datagridview contains 2 columns. "Email" and "Amount". I just want to get data from these two columns and put in data-dictionary, EMAIL as Key and the AMOUNT as Value. How could i get this?

Majid A.
  • 19
  • 1
  • 4

1 Answers1

0
Dictionary<String, Int32> myDic = new Dictionary<String, Int32>();

foreach (DataGridViewRow row in myDGV.Rows)
{
    String mail = row.Cells["Mail"].Value;
    Int32 amount = row.Cells["Amount"].Value;

    if (myDict.ContainsKey(mail))
        myDic[mail] += amount;
    else
        myDic.Add(mail, amount);
}

You can also use an indexed approach where 0 is the index of your Mail column and 1 is the index of your Amount column:

foreach (DataGridViewRow row in myDGV.Rows)
{
    String mail = row.Cells[0].Value;
    Int32 amount = row.Cells[1].Value;

    if (myDict.ContainsKey(mail))
        myDic[mail] += amount;
    else
        myDic.Add(mail, amount);
}

If your DataGridView contains rows with the same mail, my code handles this case by incrementing the respective Dictionary value.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98