浅谈DevExpress<三>:在GridView中加载动态图片

  今天的演示效果如下:在GridView中的下拉框中选中一种颜色,则后面的加载相应的图片,如下图:

1.

 

2.

3.

  下面说下实现方法:首先在项目中拉一个GirdControl,在里面创建4列:ID,Name,Color,Image,并将Color和Image分别创建repositoryItemComboBox和repositoryItemPictureEdit控件,如下图:

  将一个图片文件夹放到程序的启动目录中:

  文件夹中包含如下图片:

  接下来进行创建数据模板,先创建一个Datetable,添加数据并绑定到表格中:

private void InitData()

        {

            DataTable dt = new DataTable();

            dt.Columns.Add("ID", typeof(int));

            dt.Columns.Add("Name", typeof(string));

            dt.Columns.Add("Color", typeof(string));



            dt.Rows.Add(new object[] { 1, "Howard Snyder", "Red" });

            dt.Rows.Add(new object[] { 2, "Jaime Yorres", "Blue" });

            dt.Rows.Add(new object[] { 3, "Fran Wilson", "Orange" });

            dt.Rows.Add(new object[] { 4, "Paula Wilson", "White" });

            dt.Rows.Add(new object[] { 5, "Liz Nixon", "Red" });

            dt.Rows.Add(new object[] { 6, "Liu Wong", "Yellow" });

            dt.Rows.Add(new object[] { 7, "Carlos Hernánde", "Green" });

            dt.Rows.Add(new object[] { 8, "Carlos González", "White" });

            dt.Rows.Add(new object[] { 9, "Elizabeth Brown", "Orange" });

            dt.Rows.Add(new object[] { 10, "Hari Kumar", "Yellow" });

            dt.Rows.Add(new object[] { 11, "Michael Holz", "Yellow" });



            gridControl1.DataSource = dt;

        }

  然后创建两个全局变量用来存放图片路径和图像数据:

        string imageDir = @"Images\";

        Hashtable images = new Hashtable();    

        public string GetFileName(string color)

        {

            if (string.IsNullOrEmpty(color))

                return string.Empty;

            return color + ".jpg";

        }

  最后在Gridview中为其注册一个CustomUnboundColumnData事件,在事件中将color列和image列手动绑定并显示:

 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 (Exception)

                    {

                        

                        throw;

                    }

                    images.Add(fileName, img);

                }

                e.Value = images[fileName];

            }

        }

  到此为止,一个GridView就做好了:

 

 

 

 

 

你可能感兴趣的:(DevExpress)