0

2列のテキストデータを持つdatatableを使用していますが、行ごとに省略形を展開したいので、Dictionaryを使用しました。これは、コードのサンプルです。

   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;
     }

例外なく実行できますが、機能しません

4

2 に答える 2

0

なぜグリッド行のループで辞書を列挙するのですか?キーを検索するだけです。

また、ループの外側ではなく、ループ内の各行を追加する必要があります。そうしないと、最後の行を追加するだけです。

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);
}

編集データグリッドセルの文字列内のすべての省略語を辞書内の省略されていない単語に置き換える場合は、次のコードを使用できます。

// 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);
于 2013-03-13T10:22:47.017 に答える
0

少し変更する必要があります。そうしないと、同じ値がループで上書きされます。

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);

DataBind()最後にWebフォームを使用している場合も欠落しています

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

mz

于 2013-03-13T10:29:10.300 に答える