Question

I'm using datatable that has two columns of text data, I just want to do abbreviations expanding for each row, so I used Dictionary and here it is a sample of my code:

   private void ExpandWords()
    {    
        DataTable DT = new DataTable();
        DataRow Row;
        DT.Columns.Add(new System.Data.DataColumn("Name", typeof(string)));
        DT.Columns.Add(new System.Data.DataColumn("Label", typeof(string)));

        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("emp", "employee");
        dict.Add("dep", "department");

        for (int i = 0; i < dataGridView6.Rows.Count; i++)
        {   
            Row = DT.NewRow();
            foreach(KeyValuePair<string,string> rep in dict)
            {
              Row[0] = dataGridView6.Rows[i].Cells[0].Value.ToString().Replace    (rep.Key, rep.Value);
              Row[1] = dataGridView6.Rows[i].Cells[1].Value.ToString().Replace  (rep.Key, rep.Value);
            }
        DT.Rows.Add(Row);
        dataGridView7.DataSource = DT;
     }

it can be run without exceptions but it doesn't work

Était-ce utile?

La solution

Why do you enumerate the dictionary in the loop of the grid-rows? Just lookup the key.

You also have to add each row in the loop, not outside, otherwise you just add the last row:

for (int i = 0; i < dataGridView6.Rows.Count; i++)
{   
    Row = DT.NewRow();
    string abbrCell1 = dataGridView6.Rows[i].Cells[0].Value.ToString();
    string abbrCell2 = dataGridView6.Rows[i].Cells[1].Value.ToString();
    Row[0] = dict[abbrCell1];
    Row[1] = dict[abbrCell2];
    DT.Rows.Add(Row);
}

Edit If you want to replace all abbreviated words in the string of the datagrid cells with the not-abbreviated word in the dictionary you can use this code:

// in the loop
Row = DT.NewRow();
string abbrCell1 = dataGridView6.Rows[i].Cells[0].Value.ToString();
string abbrCell2 = dataGridView6.Rows[i].Cells[1].Value.ToString();
IEnumerable<string> unabbrWords1 = abbrCell1.Split()
    .Select(w => dict.ContainsKey(w) ? dict[w] : w);
IEnumerable<string> unabbrWords2 = abbrCell2.Split()
    .Select(w => dict.ContainsKey(w) ? dict[w] : w);
Row[0] = string.Join(" ", unabbrWords1);
Row[1] = string.Join(" ", unabbrWords2);
DT.Rows.Add(Row);

Autres conseils

You should change it a bit otherwise you'll have same value overwritten in loop:

var value1 = dataGridView6.Rows[i].Cells[0].Value.ToString();
var value2 = dataGridView6.Rows[i].Cells[1].Value.ToString();
foreach (KeyValuePair<string, string> rep in dict)
{
    value1 = value1.Replace(rep.Key, rep.Value);
    value2 = value2.Replace(rep.Key, rep.Value);
}

DT.Rows.Add(value1, value2);

You're also missing DataBind() if you're using Web Forms at the end

dataGridView7.DataSource = DT;
dataGridView7.DataBind();

mz

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top