• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 390
  • Last Modified:

C# ListView multiple colors

I have run into other problem in a ListView in C#. I'm not even sure if this is possible.

I have a textbox where a user enters a note... when he clicks the ok button the note is displayed in a listview. Is it possible for a user to enter a note using the blue font and then the blue font for that note is displayed in the listivew. And then for a second note the user picks lets say red and the red font for that note is displayed in the listview.
if yes, how would that look (code wise)
thank you.
0
MrMay
Asked:
MrMay
  • 3
  • 3
1 Solution
 
effesCommented:
You would have to provide a mechanism for the user to pick a Color, for eyample via a ColorDialog.
Then you can assign that Color to the property "ForeColor" of the TextBox and of the ListViewItem you create. Every ListViewItem in a ListView can have it's own ForeColor.

This works in Windows Forms. If you meant something else, like WPF, I would assume that there is a similar way, but I don't know enough about WPF to be sure.

Hope that helps.
0
 
somanadhaCommented:
Hi Here are the steps & code WPF (4.0). This might be more than what you are expecting, but this is the MVVM way of doing things:

1. Create a WPF Windows Application project

2. No need to change anything in the App.xaml or App.xaml.cs

3. Here is the code in MainWindow.xaml file. Just copy paste it copletely
===============================================================

<Window x:Class="ColoredItemsListBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:ColoredItemsListBox"
        Title="MainWindow" Height="411" Width="518"
        >
    <Grid Height="384" Width="578">
       
        <ListView Height="180" HorizontalAlignment="Left" Name="listView1"
                VerticalAlignment="Top" Width="491"
                ItemsSource="{Binding ListViewData}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"
                            Foreground="{Binding ElementName=ColorsComboBox, Path=SelectedItem.Brush, Mode=OneTime}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
           
        </ListView>
       
        <ComboBox Height="30" HorizontalAlignment="Left" Margin="6,189,0,0"
                Name="ColorsComboBox" VerticalAlignment="Top" Width="487"
                ItemsSource="{Binding BrushDetailsCollection}"
                SelectedItem="{Binding SelectedBrushDetails, Mode=OneWayToSource}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Rectangle Width="20" Height="20" Margin="0,2,0,2" Fill="{Binding Brush}" />
                        <TextBlock Text="{Binding ColorString}" Margin="5,2,0,2"/>
                        <TextBlock Text="{Binding BrushName}" Margin="5,2,0,2"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

        <TextBox Height="77" HorizontalAlignment="Left" Margin="10,235,0,0"
                Name="MessageTextBox" VerticalAlignment="Top" Width="483"
                Foreground="{Binding ElementName= ColorsComboBox, Path=SelectedItem.Brush}" />

        <Button Content="Add To ListView" Height="23" HorizontalAlignment="Left"
                Margin="420,339,0,0" Name="button1" VerticalAlignment="Top"
                Width="75" Command="{Binding AddToListViewCommand}"
                CommandParameter="{Binding ElementName=MessageTextBox, Path=Text, UpdateSourceTrigger=PropertyChanged}"
                />
    </Grid>
</Window>
========================================================

4. Here is the code in the MainWindow.xaml.cs

=========================================
using System.Windows;

namespace ColoredItemsListBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }
    }
}

==========================================

5. Create a class "MainWindowViewModel.cs" and copy the following contents:

=============================================================
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows.Input;
using System.Windows.Media;

namespace ColoredItemsListBox
{
    public class BrushDetails
    {
        public string BrushName
        {
            get;
            set;
        }
        public SolidColorBrush Brush
        {
            get;
            set;
        }
        public byte Red
        {
            get;
            set;
        }
        public byte Green
        {
            get;
            set;
        }
        public byte Blue
        {
            get;
            set;
        }

        public string ColorString
        {
            get
            {
                var colorString = String.Format("{{R={0}, G={1}, B={2}}}", Red, Green, Blue);
                return colorString;
            }
        }
    }

    public class ActionCommand : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public ActionCommand(Predicate<object> canExecute, Action<object> execute)
        {
            CanExecuteCallBack = canExecute;
            ExecuteCallBack = execute;
        }

        private Predicate<object> CanExecuteCallBack
        {
            get;
            set;
        }

        private Action<object> ExecuteCallBack
        {
            get;
            set;
        }

        public bool CanExecute(object parameter)
        {
            return CanExecuteCallBack != null ? CanExecuteCallBack(parameter) : false;
        }

        public void Execute(object parameter)
        {
            if (ExecuteCallBack != null)
            {
                ExecuteCallBack(parameter);
            }
        }
    }

    public class MainWindowViewModel :INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private ObservableCollection<BrushDetails> _brushDetailsCollection;
        private ObservableCollection<string> _listViewData;

        public ObservableCollection<BrushDetails> BrushDetailsCollection
        {
            get { return _brushDetailsCollection; }
            private set { _brushDetailsCollection = value; }
        }

        public ObservableCollection<string> ListViewData
        {
            get { return _listViewData; }
            private set { _listViewData = value; }
        }

        public ICommand AddToListViewCommand
        {
            get;
            private set;
        }

        public MainWindowViewModel()
        {
            _brushDetailsCollection = new ObservableCollection<BrushDetails>();

            var brushesType = typeof(Brushes);
            var brushesProps = brushesType.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty);
            var brushDetails = new BrushDetails();
            brushesProps.ToList().ForEach(brush =>
                {
                    brushDetails = new BrushDetails();
                    brushDetails.BrushName = brush.Name;
                    brushDetails.Brush = (SolidColorBrush) brush.GetGetMethod().Invoke(null, null);
                    brushDetails.Red = brushDetails.Brush.Color.R;
                    brushDetails.Green = brushDetails.Brush.Color.G;
                    brushDetails.Blue = brushDetails.Brush.Color.B;
                    _brushDetailsCollection.Add(brushDetails);
                });

            AddToListViewCommand = new ActionCommand(CanExecute, Execute);
            _listViewData = new ObservableCollection<string>();
        }

        private bool CanExecute(object param)
        {
            bool rVal = false;
            if ((param != null) && !String.IsNullOrEmpty(param.ToString()))
            {
                rVal = true;
            }
            return rVal;
        }

        private void Execute(object param)
        {
            ListViewData.Add(param.ToString());
        }
    }
}

=============================================================
0
 
MrMayAuthor Commented:
So I've added a check box next to my "note" text-box...  Its all saved to an access database. If the check-box is checked a True goes into a column "Critical" in the access database.
Now here is my code for displaying all info to a list-view.

for (int i = 0; i < ds.Tables["Notes"].Rows.Count; i++)
                {
                   
    listView2.Items.Add(ds.Tables["Notes"].Rows[x]["NotesID"].ToString());
    listView2.Items[x].SubItems.Add(ds.Tables["Notes"].Rows[x]["Profile"].ToString() + " " + (ds.Tables["Notes"].Rows[x]["Department"].ToString()));  
    listView2.Items[x].SubItems.Add( ((DateTime)ds.Tables["Notes"].Rows[x]["Tim"]).ToString("HH:mm"));
    listView2.Items[x].SubItems.Add(ds.Tables["Notes"].Rows[x]["Notee"].ToString());
                }


I'm assuming I will need a if statement that goes through and checks if a column "Critical" in the database is equal to true. If Yes... then print the whole line of entry in the list view in red.. such as this
               listView2.Items[x].ForeColor = Color.Red;
if the "Crtical" column is equal to False... just print it in black.

Is my thought process correct? if yes... can someone please help me out with the code... no idea how to write this.
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
effesCommented:
Your idea is right. For every row in the table check the value of "Critical" and set the ForeColor accordingly.
I modified the code you posted a bit and inserted the part for setting the color:
foreach (DataRow row in ds.Tables["Notes"].Rows)
{
    ListViewItem item = new ListViewItem(row["NotesID"].ToString());
    ListView2.Items.Add(item);
    item.SubItems.Add(row["Profile"].ToString() + " " + row["Department"].ToString());
    item.SubItems.Add(((DateTime)row["Time"]).ToString("HH:mm"));
    item.SubItems.Add(row["Notee"].ToString());

    if ((bool)row["Critical"])
    {
        item.ForeColor = Color.Red;
    }
}

Open in new window

Please try if this works for you.
If you find any errors or just have a question regarding my modifications to your code, just ask.
0
 
MrMayAuthor Commented:
Hello effes...
Thank you for your help... I am however having a bit of a problem with it.

You see in my access database, the "Critical" column is a string variable. So I either write 'True' or 'False'.
So.... if critical note then Critical column gets a True if not critical then Critical column gets a False.

Your line of code..... if ((bool)row["Critical"])   I think I need to modify it to actually check if its a True or a False... am I right.... How would I make change to that line.

Thank you in advance.
0
 
MrMayAuthor Commented:
Hey effes....

I think I figured it out... it works too.

 if ((string)row["Critical"] == "True")
                  {
                     item.ForeColor = Color.Red;
                  }

thank you so so much for your help.     :)
0
 
effesCommented:
You're welcome.

Well done on the switch from bool to string.
I kinda assumed "Critical" was a boolean value, sorry!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now