Solved

C# ListView multiple colors

Posted on 2011-09-16
7
350 Views
Last Modified: 2013-12-17
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
Comment
Question by:MrMay
  • 3
  • 3
7 Comments
 
LVL 6

Expert Comment

by:effes
ID: 36551866
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
 

Expert Comment

by:somanadha
ID: 36554753
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
 

Author Comment

by:MrMay
ID: 36576562
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 6

Expert Comment

by:effes
ID: 36576839
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
 

Author Comment

by:MrMay
ID: 36580044
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
 

Author Comment

by:MrMay
ID: 36580092
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
 
LVL 6

Accepted Solution

by:
effes earned 500 total points
ID: 36582087
You're welcome.

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now