winform中的 datagridview 怎样显示数据库中的图片(数据库中存的是路径)
C# winform中的 datagridview 怎样显示数据库中的图片(数据库中存的是路径),我通过查找数据库,数据库属性有书名,图片,作者,怎么输出?
[解决办法]
添加dataGridView的DataGridViewImageColumn类型类,绑定一下就可以了。
[解决办法]
[解决办法]
首先在 datagridview 中建立一列 DataGridViewImageColumn 图片列,DataPropertyName 属性指定数据库图片路径的列名,然后注册 CellFormatting 事件,并在类窗体代码中定义一个项全局变量
- C# code
// 全局变量,储存图片private SortedDictionary<string, Image> slist = new SortedDictionary<string, Image>();private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e){ if (e.ColumnIndex == 显示图片列的索引) { if (e.Value is string) { // 图片路径 var key = (string)e.Value; Image img; // 保存在全局变量中,避免重复加载 if (!slist.TryGetValue(key, out img)) { img = Image.FromFile(key); slist.Add(key, img); } e.Value = img; e.FormattingApplied = true; } }}
[解决办法]
- C# code
private void demoGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (demoGrid.Columns[e.ColumnIndex].Name.Equals("Image")) { string path = System.Windows.Forms.Application.StartupPath + @"/1.gif"; e.Value = GetImage(path); } } public System.Drawing.Image GetImage(string path) { System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open); System.Drawing.Image result = System.Drawing.Image.FromStream(fs); fs.Close(); return result; }