المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Control derived from Listbox not drawing properly



C# Programming
01-30-2010, 01:00 AM
I've got the following code running and the idea is that a row in the DB has a coloured letter in it to denote customer or supplier etc. The first row i highlight seems to vanish, the background for the row is blue and the selected index is set so that's all nice but the text disappears. If i click the row a second time the row unselects and the text comes back.

public partial class CompanyListControl : ListBox
{
int _previousIndex = 0;
public CompanyListControl()
{
InitializeComponent();
this.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
if (!DesignMode)
{
e.DrawBackground();
if (this.SelectedIndex == e.Index)
{
if (_previousIndex != e.Index)
{
InvalidateItem(_previousIndex);
DrawSelected(e);
_previousIndex = e.Index;
}
}
else
{
DrawUnselected(e);
}
}
}
public void InvalidateItem(int index)
{
if ((index < 0) || (index >= this.Items.Count))
return;
object InvalidatedObject = this.Items[index];
this.Items.RemoveAt(index);
this.Items.Insert(index, InvalidatedObject);
}
private void DrawSelected(DrawItemEventArgs e)
{
if (e.Index == -1) return;
int RowWidth = e.Bounds.Width;
Font f = new Font("Arial Black", e.Font.Size);
Size s = TextRenderer.MeasureText("C", f);
int SalesPos = 0;
float PurchasePos = s.Width * 0.7f;
float TextPos = PurchasePos * 2;
int VerticalPos = e.Bounds.Top;
e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, Brushes.White, TextPos, e.Bounds.Top);
e.Graphics.DrawString("C", f, Brushes.Red, SalesPos, VerticalPos);

}
private void DrawUnselected(DrawItemEventArgs e)
{
int RowWidth = e.Bounds.Width;
Font f = new Font("Arial Black", e.Font.Size);
Size s = TextRenderer.MeasureText("C", f);
int SalesPos = 0;
float PurchasePos = s.Width * 0.8f;
float TextPos = PurchasePos * 2;
int VerticalPos = e.Bounds.Top;
e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, Brushes.Black, TextPos, e.Bounds.Top);
e.Graphics.DrawString("C", f, Brushes.Red, SalesPos, VerticalPos);
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged(e);
this.Invalidate();
}
}

Does anyone have any ideas what might be wrong? I've added and removed all sorts of bits from the code and it doesn't seem to change the behaviour very much at all (to the point that I put some break points in just to check that this code was actually being run)

Thanks

Russ