在 C# WinForm环境中,如何将图片保存入数据库,又如何将图片从数据库中取出显示在Picture控件中?谢谢!

ColorSM 2002-04-29 08:26:20
在 C# WinForm环境中,如何将图片保存入数据库,又如何将图片从数据库中取出显示在Picture控件中?谢谢!
...全文
212 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
acptvb 2002-04-30
  • 打赏
  • 举报
回复
感谢您使用微软产品。

在C#中,可以通过如下的步骤来实现将image文件写入数据表的image字段:
1,创建一个FileStream对象,通过该FileStream对象来读取指定的image文件;
2,根据生成FileStream对象,创建byte[]数据,通过FileStream对象的Read方法将数据写入byte[]数组中;
3,将上述byte[]数组赋予数据表的image字段,写入数据表中;
关于将数据表中的iamge字段显示在PictureBox控件中,请参考如下答复:
http://www.csdn.net/expert/topic/675/675865.xml?temp=.655163

下面提供一段示例程序,供您参考:
private void btnAdd_Click(object sender, System.EventArgs e)
{
// Fill a DataSet
DataSet ds = new DataSet();
string connString = "Server=SHA-RICKIE-01;DataBase=test;uid=user;pwd=user";
string sqlString = "Select * from Students";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter(sqlString,conn);
SqlCommandBuilder MyCB = new SqlCommandBuilder(sqlDataAdapter1);

sqlDataAdapter1.Fill(ds, "students");
DataTable TheTable = ds.Tables[0];
// Create a new row in Memory
DataRow aRow = TheTable.NewRow();
// Insert the information from the dialog into the Table
aRow["name"] = txtboxname.Text;
aRow["age"] = txtboxage.Text;
// 创建一个FileStream对象用来读取image文件,其中FileName 为该image的完整文件名
string FileName = txtboxFilename.Text;
FileStream fs = new FileStream (FileName, FileMode.OpenOrCreate,
FileAccess.Read);
// Read the Data into the Byte Array
byte[] MyData = new byte[fs.Length];
fs.Read(MyData, 0, (int)fs.Length);
fs.Close();
// Assign the DataRow Picture Column to the Byte Array to populate it in the DataRow
aRow["image"] = MyData;
// Add the DataRow to the DataTable
TheTable.Rows.Add(aRow);
// 写数据记录到数据库表中
sqlDataAdapter1.Update(ds, "students");
MessageBox.Show("A student added.");
}


关于FileStream类的更详细信息,请参考MSDN:
ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemIOFileStreamMembersTopic.htm

— 微软全球技术中心 VB支持中心

本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利。具体事项可参见使用条款(http://support.microsoft.com/directory/worldwide/zh-cn/community/terms_chs.asp)。
为了为您创建更好的讨论环境,请参加我们的用户满意度调查(http://support.microsoft.com/directory/worldwide/zh-cn/community/survey.asp?key=(S,49854782))。

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧