用戶控件代碼:將數據庫中的圖片顯示到每個usercontrol的picturebox?
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
textBox1.Text = value;
}
}
表格代號:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName, Image from Employee", myDatabaseConnection))
{
int i = 0;
SqlDataReader DR1 = SqlCommand.ExecuteReader();
while (DR1.Read())
{
i++;
UserControl2 usercontrol = new UserControl2();
usercontrol.Tag = i;
usercontrol.LastName = (string)DR1["LastName"];
flowLayoutPanel1.Controls.Add(usercontrol);
}
}
}
有了上面的代碼,我可以從每個用戶控件的文本框數據庫顯示每個姓氏。如何將數據庫中的圖片顯示到每個usercontrol的picturebox?
這是我從數據庫中顯示單個圖像:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName, Image from Employee where ID = @a", myDatabaseConnection))
{
SqlCommand.Parameters.AddWithValue("@a", textBox1.Text);
DataSet DS = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(SqlCommand);
da.Fill(DS, "Images");
var imagesTable = DS.Tables["Images"];
var imagesRows = imagesTable.Rows;
var count = imagesRows.Count;
if (count <= 0)
return;
var imageColumnValue =
imagesRows[count - 1]["Image"];
if (imageColumnValue == DBNull.Value)
return;
var data = (Byte[])imageColumnValue;
using (var stream = new MemoryStream(data))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
}
Did'nt處理空值。但是還是特別感謝你爲wirecontrols。 :) –
很容易事先檢查null。如果沒有關聯的圖像,您可以創建一個只接受姓氏的不同重載.... –