0

I have set up a data grid view and linked it to my data and filled it with the adapter and all that is working just fine. What I would like to do is add a column to the beginning of the data grid view and add an image to the first column that has the file name of the current first column of which will wind up as the second column.

I have added the column and set it up for images already and also set a default image if the value is not set. I am having trouble figuring out how to read what is in column2 and then loading the image with the file name (edited a bit to match my naming schemes) into column1. I cant figure out if I need to do this to the grid view, the datasettableadapter, or some other place. I tried iterating throw the rows to read cell2 then load image for cell1 but I can't set currentrow.

I ended up using CellPainting because CellFormating was giving me some strange output. Below is the code I use. Cells[0] is the cell I would like to put the image in. Cells[1] is the name of the image that I use as file name.

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        string monsterName = "";

        try
        {
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "monsterNameDataGridViewTextBoxColumn")
            {
                if (e.Value != null && e.RowIndex > -1)
                {
                    monsterName = (string)this.dataGridView1.Rows[e.RowIndex].Cells[1].Value;
                    this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = new Bitmap(@"C:\Users\Chad\Pictures\Dark Summoner\C_" + monsterName + @".png");
                }
            }
        }

        catch (ArgumentException)
        {
           toolStripStatusLabel1.Text = monsterName + " image file does not exist.";
        }

    }
4

1 回答 1

0

您可以通过几种方式处理此问题。

1) 处理 datagridview 的 CellFormatting 事件并在其中填充单元格的图像。该事件有一个参数可以访问它试图格式化的当前行/列。因此,您可以从单元格 2 中读取图像文件,并在此基础上设置单元格 1 的图像。

2) 在数据源中预填充图像数据。因此,如果您的数据适配器正在填充数据表,例如,您可以在加载数据表后加载/填充数据表中的图像。

于 2012-08-14T23:04:15.327 回答