[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# ListView multiple colors

Posted on 2011-09-16
7
Medium Priority
?
370 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
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
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 2000 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses

831 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