user1851622 user1851622 - 3 months ago 26
C# Question

DataGridViewImageColumn Image layout doesn't work

I'm trying to display an image on datagridview with an image column; however,
it appears stretched vertically and squished horizontally. I'm not sure what's limiting it to be displayed this way.

Grid Generation

gvPackage.Columns.Clear();

gvPackage.AutoGenerateColumns = false;
DataGridViewColumn[] cols = new DataGridViewColumn[5];
GridColumn gc = null;

cols[0] = new DataGridViewTextBoxColumn();
cols[0].DataPropertyName = "ID";
cols[0].Name = "ID";
cols[0].Visible = false;

cols[1] = new DataGridViewTextBoxColumn();
cols[1].DataPropertyName = "iLive";
cols[1].Name = "iLive";
cols[1].Visible = false;

cols[2] = new DataGridViewTextBoxColumn();
cols[2].DataPropertyName = "iExplicit";
cols[2].Name = "iExplicit";
cols[2].Visible = false;

cols[3] = new DataGridViewImageColumn();
cols[3].Name = "Icon";
cols[3].Width = 70;
cols[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
cols[3].FillWeight = 1F;

cols[4] = new DataGridViewTextBoxColumn();
cols[4].DataPropertyName = "sName";
cols[4].Name = "sName";
cols[4].Width = 216;
cols[4].FillWeight = 50.5166F;

gvPackage.Columns.AddRange(cols);

List<Package> _pl = _______Manager.SHARED_RES;

foreach (Package p in _pl)
{
gvPackage.Rows.Add(
p.ID,
p.iLive,
p.iExplicit,
gImageList.Images["imgNoExplicitNoLive"],
p.sName
);
}


Cell Formatting:

private void gvPackage_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (gvPackage.Columns[e.ColumnIndex].Name == "Icon")
{
bool isExp = this.gvPackage.Rows[e.RowIndex].Cells[2].Value.ToString() == "1";
bool isLive = this.gvPackage.Rows[e.RowIndex].Cells[1].Value.ToString() == "1";
if (isExp && isLive)
{
e.Value = gImageList.Images["imgExplicitLive"];

}
else
if (!isExp && isLive)
{
e.Value = gImageList.Images["imgNoExplicitLive"];
}
else
if (isExp && !isLive)
{
e.Value = gImageList.Images["imgExplicitNoLive"];
}
else
if (!isExp && !isLive)
{
e.Value = gImageList.Images["imgNoExplicitNoLive"];
}
}
}


Bad image:

Incorrect image

The source image:
Source image

Any help would be appreciated.

TaW TaW
Answer

Start by checking the gImageList.Imagesize!

It's default will use square image sizes of 16x16!

Change that to the size of your Images before you load them:

gImageList.ImageSize = new Size(61,12);

Note that all Images need to have the same size. If they haven't you should change them; much better than the stretching the ImageList will apply!

Also note that the Images in an ImageList are limited to 256x256 pixels.

You may also want to check if you are happy with its ColorDepth = Depth8Bit

Obviously your Column/Cell needs to provide enough space as well!