如何在 DevExpress.XtraGrid.GridControl 顯示圖片列。 方法很多,我把它們逐一寫在附言中,方便大家分情況合理使用。
第 1 條附言 · 6 月前
GridControl一列的ColumnEdit屬性中選擇PictureEdit,一個RepositoryItemPictureEdit添加完成。列的FieldName設置為Image列名,如img。
GridControl綁定的數據,不管是DataTable、List或者其他源,添加一個列,列名為img。 以DataTable為例:
Image xx=Image.FromFile(
"xxx"
),yy=Image.FromFile(
"yyy"
);
dt.Columns.Add(
"img"
);
foreach
(DataRow dr
in
dt.Rows)
{
if
(dr[
"imgflag"
].ToString()==
"1"
)
dr[
"img"
]=xx;
else
dr[
"img"
]=yy;
}
|
第 2 條附言 · 6 月前
上一篇介紹的是直接使用Image類型,也可以使用byte[]。
如果數據庫中直接存的二進制,沒什么好說的,直接DataSource=dt綁定完成即可。
下面是一個image路徑的例子。
private
void
showData(List list) {
DataTable dt =
new
DataTable(
"OneEmployee"
);
dt.Columns.Add(
"Caption"
,System.Type.GetType(
"System.String"
));
dt.Columns.Add(
"Department"
,System.Type.GetType(
"System.String"
));
dt.Columns.Add(
"PhotoName"
,System.Type.GetType(
"System.Byte[]"
));
for
(
int
i = 0; i < list.Count; i++) {
DataRow dr = dt.NewRow();
dr[
"Caption"
] = list[i].Name;
dr[
"Department"
] =list[i].Department;
string
imagePath =
@"D:/C#/photos/"
+ list[i].PhotoPath;
dr[
"PhotoName"
] = getImageByte(imagePath);
dt.Rows.Add(dr);
}
gridControl1.DataSource = dt;
}
//返回圖片的字節流byte[]
private
byte
[] getImageByte(
string
imagePath) {
FileStream files =
new
FileStream(imagePath,FileMode.Open);
byte
[] imgByte =
new
byte
[files.Length ];
files.Read(imgByte,0, imgByte.Length);
files.Close();
return
imgByte;
}
|
第 3 條附言 · 6 月前
還有一種方法,使用CustomUnboundColumnData事件
1. 創建了一個非綁定列並設置其相應的屬性,屬性設置如下:
FieldName設為Image (該字段名必須是唯一的) UnboundType設為 UnboundColumnType.Object
ColumnEdit設為RepositoryItemPictureEdit類的實例(該操作PictureEdit 為該列的內置編輯器)
2. 處理View的CustomUnboundColumnData事件,用於為非綁定列填充數據。
在該事件中需加載圖片,將其存放在一個hashtable中,然后再將其提供給對應
的單元格。
關鍵代碼:
//獲取文件路徑
string
GetFileName(
string
color) {
if
(color ==
null
||color ==
string
.Empty)
return
string
.Empty;
return
color +
".jpg"
;
}
//處理CustomUnboundColumnData事件,為非綁定列填充數據
private
void
gridView1_CustomUnboundColumnData(
object
sender,
DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
{
if
(e.Column.FieldName ==
"Image"
&& e.IsGetData) {
GridView view = sender
as
GridView;
string
colorName = (
string
)((DataRowView)e.Row)[
"Color"
];
string
fileName = GetFileName(colorName).ToLower();
if
(!Images.ContainsKey(fileName))
{
Image img =
null
;
try
{
string
filePath = DevExpress.Utils.FilesHelper.FindingFileName(Application.StartupPath, ImageDir+ fileName,
false
);
img = Image.FromFile(filePath);
}
catch
{ }
Images.Add(fileName, img);
}
e.Value = Images[fileName];
}
}