0

我有一个应用程序,其中数据存储在单词表中。我想把表格的内容放到gridview中。有没有可能这样做。下面是代码的一部分

private void FillDocumentInfo(Word._Document reportDoc, string heading, Hashtable documentInfo)
{
    object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
    object oMissing = System.Reflection.Missing.Value;

    Word.Paragraph oPara;
    object oRng = reportDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara = reportDoc.Content.Paragraphs.Add(ref oRng);
    oPara.Range.InsertParagraphBefore();
    oPara.Range.Font.Size = 20;
    oPara.Range.Text = heading;
    oPara.Range.Font.Bold = 1;

    oPara.Range.InsertParagraphAfter();
    Word.Range wrdRng = reportDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    Word.Table oTable;
    wrdRng = reportDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = reportDoc.Tables.Add(wrdRng, documentInfo.Count, 2, ref oMissing, ref oMissing);
    oTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;

    IDictionaryEnumerator _enumerator = documentInfo.GetEnumerator();
    int r = 1, c = 1;
    while (_enumerator.MoveNext())
    {
        oTable.Rows[r].Range.Font.Bold = 0;
        oTable.Rows[r].Range.Font.Italic = 1;
        oTable.Cell(r, c++).Range.Text = _enumerator.Key.ToString();
        oTable.Cell(r++, c--).Range.Text = _enumerator.Value.ToString();

        List<string> cellValues = new List<string>();

        string cellContents = _enumerator.Key.ToString();
        string cellcont = _enumerator.Value.ToString();
        // add the cell contents to the array, but remove the strange termination character on the end of the data
        cellValues.Add(cellContents.Remove(cellContents.Length - 1));
        cellValues.Add(cellcont.Remove(cellcont.Length - 1));

        AddWordTableRow(cellValues);
    }                                    
    documentInfo.Clear();
}

public void AddWordTableRow1(string name, string address)
{
    dataGridView1.Rows.Add(new string[] { name, address});
}

public void AddWordTableRow(List<string> cellValues)
{
    DataGridViewRow dr = new DataGridViewRow();
    dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; 
    AddWordTableRow1(cellValues[0], cellValues[1]);
}

这里出现跨线程操作异常

4

1 回答 1

0

您可能需要调用 AddWordTableRow1() 方法。您可以使用您在评论中发布的操作尝试此操作,也可以尝试使用我用于调用的这个有用的扩展方法;

public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
        {
            if (@this.InvokeRequired)
            {
                @this.Invoke(action, new object[] { @this });
            }
            else
            {
                action(@this);
            }
        }

在你的情况下,像这样使用它;

dataGridView1.InvokeEx(() => dataGridView1.Rows.Add(new string[] { name, address}));

编辑#1:

此外,如果您希望填充行/列以显示您放入其中的数据,请尝试修改数据网格属性;AutoSizeColumnsModeAutoSizeRowsMo​​de

于 2013-04-23T09:36:11.923 回答