반응형
블로그 이미지
sense.45

공지사항

최근에 올라온 글

최근에 달린 댓글

글 보관함

calendar

1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

C# ListBox에 색깔넣기

2018. 4. 6. 19:14 | Posted by sense.45
반응형

C# ListBox에 색을 넣으면 가독성이 좋아집니다.


색을 넣어 보겠습니다.



끝.




ㅎㅎ





1. Class를 하나 만듭니다.

public class MyListBoxItem

{

        public MyListBoxItem(Color c, string m)

        {

            ItemColor = c;

            Message = m;

        }

        public Color ItemColor { get; set; }

        public string Message { get; set; }

}



2. 리스트박스의 DrawItem 이벤트를 추가합니다.



        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)

        {

            if (e.Index == -1)   return;    //아이템이 없는 경우 는 할 일이 없습니다.


            MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; 

            if (item != null)

            {

                e.Graphics.DrawString( 

                    item.Message, 

                    listBox1.Font, 

                    new SolidBrush(item.ItemColor), 

                    0, 

                    e.Index * listBox1.ItemHeight 

                );

            }

            else

            {

                // The item isn't a MyListBoxItem, do something about it

            }


        }



3. 이제 버턴이벤트나 기타 모듈에서 아이템을 추가합니다.


listBox1.Items.Add(new MyListBoxItem(Color.Red, "빨간색 ==== Red Color"));

listBox1.Items.Add(new MyListBoxItem(Color.Blue, "파란색 ==== Blue Color"));



이상태에서 실행하면 



이렇게 나옵니다......ㅠㅠ





DrawMode 를o OwnerDrawFixed로 변경하여야 합니다.

(Normal만 아니면 됩니다.)




출처

https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.drawitem(v=vs.110).aspx


https://stackoverflow.com/questions/6896151/c-sharp-change-listbox-items-color


https://stackoverflow.com/questions/29173517/winforms-simplest-way-to-change-listbox-text-color-on-the-fly



반응형

'C#' 카테고리의 다른 글

c# List FindIndex  (0) 2018.04.04
C#ListBox에서 아래로 스크롤 하기  (0) 2018.04.02
c#배열에 SqlDataReader 결과를 넣는 방법  (0) 2018.03.30
DLL 버전이 알고 싶은 경우  (0) 2018.03.22