图像数据绑定到pictureBox
我试图通过两种方法将数据集“data_set”中数据表“Applicant’s Details”中的“Applicant’s Image”列中的图像绑定。 但是当我运行表单应用程序时,我看不到图片框中显示的图像“imgusr”。 我的绑定源名称是“bindSource”。
假设data_set正确地检索了所有内容,那么图像没有加载到图片框“imgusr”会有什么问题?
另外,sizeMode的picturebox属性为“zoom”。
private void Update_Load(object sender, EventArgs e){ data_set = blobj.srcforVU(); bindSource.DataSource = data_set; bindSource.DataMember = "Applicant's Details"; lbidvalue.DataBindings.Add(new Binding("Text", bindSource, "Applicant's ID", false)); //method 1 //Binding binding = new Binding("Image", bindSource, "Applicant's Image", true, DataSourceUpdateMode.OnPropertyChanged); //binding.Format += new ConvertEventHandler(binding_Format); //imgusr.DataBindings.Add(binding); //method 2 imgusr.DataBindings.Add(new Binding("Image", bindSource, "Applicant's Image", true)); tbfname.DataBindings.Add(new Binding("Text", bindSource, "First Name", true)); tblname.DataBindings.Add(new Binding("Text", bindSource, "Last Name", true)); tbgender.DataBindings.Add(new Binding("Text", bindSource, "Gender", true)); tbbdate.DataBindings.Add(new Binding("Text", bindSource, "Birth Date", true)); tbmob.DataBindings.Add(new Binding("Text", bindSource, "Mobile No", true)); tbadd.DataBindings.Add(new Binding("Text", bindSource, "Address", true)); tbcntry.DataBindings.Add(new Binding("Text", bindSource, "Country", true)); tbmstat.DataBindings.Add(new Binding("Text", bindSource, "Is Married", true)); tbspfname.DataBindings.Add(new Binding("Text", bindSource, "Spouse's First Name", true)); tbsplname.DataBindings.Add(new Binding("Text", bindSource, "Spouse's Last Name", true)); tbspage.DataBindings.Add(new Binding("Text", bindSource, "Spouse's Age", true)); tbchild.DataBindings.Add(new Binding("Text", bindSource, "No Of Children", true)); bindNavigator.BindingSource = bindSource; afterloadoptions(); } public void binding_Format(object sender, ConvertEventArgs e) { string path = (string)e.Value; e.Value = Image.FromFile(path); }
解决方案可以像这样简单:
imgusr.DataBindings.Add(new Binding("Image", data_set, "yourtablename.yourcolumnname", true));
请注意,您需要通过将最后一个参数( enableFormatting
)设置为true
来告诉Binding
执行格式化 。 处理图像不再需要特殊代码。
另请注意,我没有尝试使用必要的格式来在列名中使用空格和撇号。 我建议使用标准名称!
最后确保设置要在DataSet
使用的Table
的TableName
属性:
data_set.Tables[0].TableName = "yourtablename";
从您的讨论更新似乎您没有正确地将图像数据保存到您的dbms。 这是您的例程的一个版本,应该更好地工作:
byte[] img_byte = null; long imgfilelength = 0; private void StoreImage(string ChosenFile) { try { using (Image img = Image.FromFile(ChosenFile)) using (MemoryStream ms = new MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Close(); img_byte = ms.ToArray(); imgfilelength = img_byte.Length; } } catch (Exception e) { MessageBox.Show(e.ToString()); } }
测试很简单:
private void test_button_Click(object sender, EventArgs e) { StoreImage(someImageFile); using (MemoryStream ms = new MemoryStream(img_byte)) { aPictureBox.Image = Image.FromStream(ms); } }
确保使用正确的文件格式,例如Png
或Jpeg
等。