【发布时间】:2019-02-22 16:10:21
【问题描述】:
拜托,我非常感谢任何人都可以帮助我解决以下问题。
我有一个 Access 数据库,我想将它加载到 ListBox。
我将 ListBox DrawMode 设置为 OwnerDrawFixed,但是当我运行应用程序时,它显示 (System.Data.DataRowView) 而不是所有数据库记录。
我必须说它在 Normal DrawMode 下运行良好。
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
ListBox1.DataSource = GetData();
ListBox1.DisplayMember = "empName";
}
DataTable dt;
private DataTable GetData()
{
dt = new DataTable();
using (OleDbConnection myConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
using (OleDbCommand myQuery = new OleDbCommand("select empName from empTable", myConn))
{
myConn.Open();
OleDbDataReader myReader = myQuery.ExecuteReader();
dt.Load(myReader);
}
}
return dt;
}
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
bool isItemSelected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int itemIndex = e.Index;
if (itemIndex >= 0 && itemIndex < ListBox1.Items.Count)
{
Graphics g = e.Graphics;
SolidBrush backgroundColorBrush = new SolidBrush((isItemSelected) ? Color.FromArgb(255, 64, 64, 64) : Color.FromArgb(0,64,64,64));
g.FillRectangle(backgroundColorBrush, e.Bounds);
// Set text color
string itemText = ListBox1.Items[itemIndex].ToString();
SolidBrush itemTextColorBrush = (isItemSelected) ? new SolidBrush(Color.White) : new SolidBrush(Color.LightGray);
g.DrawString(itemText, e.Font, itemTextColorBrush, ListBox1.GetItemRectangle(itemIndex).Location);
// Clean up
backgroundColorBrush.Dispose();
itemTextColorBrush.Dispose();
}
e.DrawFocusRectangle();
}
再次感谢您。
【问题讨论】:
-
这通常是没有向列表框添加字符串而是某些对象(属于没有好的 ToString 方法的类)的症状。你不应该也设置一个 ValueMember 吗?
-
@TaW,谢谢。我非常努力。但还是想不通。请帮我写代码。
标签: c# .net winforms ms-access graphics