我在数据库中有用户数据(名称、用户名、图像),我需要在组合框中列出名称和 ID。When an item in the combo box is selected it should display a picture. 我创建了一个 User 和一个 UserDB 类。在我的用户类中,我有以下代码:
public class User
{
private String u_firstname;
private String u_lastname;
private String u_username = string.Empty;
private Byte [] u_image;
private Byte [] u_template;
public User(OleDbDataReader dr)
{
u_firstname = dr["USER_FIRST_NM"].ToString();
u_lastname = dr["USER_LAST_NM"].ToString();
u_username = dr["USER_NAME"].ToString();
u_image = (Byte [])dr["USER_IMAGE"];
u_template = (Byte [])dr["USER_TEMPLATE"];
}
}
在我的 UserDB 类中,我有以下代码:
public class UserDB
{
public static String workingDirectory = System.IO.Directory.GetCurrentDirectory();
public static String dbProvider = "Microsoft.ACE.OLEDB.12.0";
public static String dbName = "Users_DB.accdb";
public static String dbConnString = String.Format(@"Provider={0};Data Source={1}\Data\{2}", dbProvider, workingDirectory, dbName);
public User[] usersInDatabaseList()
{
User u;
List<User> clist = new List<User>();
OleDbConnection cn = new OleDbConnection(dbConnString);
String strSQL = "SELECT USER_FIRST_NM, USER_LAST_NM, USER_NAME, USER_IMAGE, USER_TEMPLATE FROM KF001_USERS";
OleDbCommand cm = new OleDbCommand(strSQL, cn);
OleDbDataReader dr;
cn.Open();
dr = cm.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
u = new User(dr);
clist.Add(u);
}
cn.Close();
return clist.ToArray();
}
}
在我的 mainForm 上,我有以下用于组合框的方法:
public void FillDropDownList()
{
try
{
//int i;
UserDB db = new UserDB();
User[] userList = db.usersInDatabaseList();
comboBoxUsersEnrolled.Items.AddRange(userList);
comboBoxUsersEnrolled.DisplayMember = ?
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我完全不知道如何让我的数据库值显示在组合框中。我也不确定如何在选择项目时显示图片。任何人都可以帮助或引导我朝着正确的方向前进。
所以我将 filldropdownlist 方法更改为以下内容:
public void FillDropDownList()
{
UserDB db = new UserDB();
User[] userList = db.cList();
for (int i = 0; i < userList.Length; i++)
{
comboBoxUsersEnrolled.Items.Add(userList[i]);
comboBoxUsersEnrolled.DisplayMember = "ComboName";
if (comboBoxUsersEnrolled.SelectedIndex > 0 )
{
byte[] pictureByteReader = (userList[i].UserImage);
MemoryStream ms = new MemoryStream(pictureByteReader);
Image picture = Image.FromStream(ms);
picBoxCapture.Image = picture;
}
}
}
我正在尝试添加到我的组合框,同时如果选择了该项目,则将图片发送到图片框。我的代码什么都不做。没有错误或任何东西。帮助!