C#窗体程序,DataGridView代码绑定MySQL数据库中含有图片的字段列并显示图片
数据库表AAA,字段:id,name,image;image为String,存放的是本地的图片的路径求编写DataGridView的代码绑定数据方法:DataBind()...
数据库表AAA,字段:id,name,image;
image为String,存放的是本地的图片的路径
求编写DataGridView的代码绑定数据方法:DataBind()
要求,image在第一列显示为图片,然后id、name 展开
image为String,存放的是本地的图片的路径
求编写DataGridView的代码绑定数据方法:DataBind()
要求,image在第一列显示为图片,然后id、name 展开
展开全部
DataTable dt = new DataTable();
using (MySqlConnection con = new MySqlConnection())
{
con.ConnectionString = "Data Source=127.0.0.1;Initial Catalog=mysql;User ID=root;password=";
con.Open();
string query = string.Format("select id ,name ,image from AAA");
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
dt.Load(cmd.ExecuteReader());
}
}
dt.Columns.Add("图片",System.Type.GetType("System.Byte[]"));
DataTable dt2 = dt.Clone();
foreach (DataRow item in dt.Rows)
{
DataRow dr = dt2.NewRow();
dr[0] = item[0];
dr[1] = item[1];
dr[2] = item[2];
using (FileStream fs = new FileStream(item[2].ToString(), FileMode.Open))//根据路径取得图片
{
using (BinaryReader br = new BinaryReader(fs))
{
dr["图片"] = br.ReadBytes((int)fs.Length);
}
}
dt2.Rows.Add(dr);
}
dataGridView1.DataSource = dt2;
dataGridView1.Columns["图片"].DisplayIndex = 0;
dataGridView1.Columns["id"].DisplayIndex = 1;
dataGridView1.Columns["name"].DisplayIndex = 2;
dataGridView1.Columns["image"].Visible = false ;
using (MySqlConnection con = new MySqlConnection())
{
con.ConnectionString = "Data Source=127.0.0.1;Initial Catalog=mysql;User ID=root;password=";
con.Open();
string query = string.Format("select id ,name ,image from AAA");
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
dt.Load(cmd.ExecuteReader());
}
}
dt.Columns.Add("图片",System.Type.GetType("System.Byte[]"));
DataTable dt2 = dt.Clone();
foreach (DataRow item in dt.Rows)
{
DataRow dr = dt2.NewRow();
dr[0] = item[0];
dr[1] = item[1];
dr[2] = item[2];
using (FileStream fs = new FileStream(item[2].ToString(), FileMode.Open))//根据路径取得图片
{
using (BinaryReader br = new BinaryReader(fs))
{
dr["图片"] = br.ReadBytes((int)fs.Length);
}
}
dt2.Rows.Add(dr);
}
dataGridView1.DataSource = dt2;
dataGridView1.Columns["图片"].DisplayIndex = 0;
dataGridView1.Columns["id"].DisplayIndex = 1;
dataGridView1.Columns["name"].DisplayIndex = 2;
dataGridView1.Columns["image"].Visible = false ;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询