Can a c# combobox have two datasources diffrentiated by sorting (Source 1 entries at the top) and Text color (Source 1 entries colored blue for instance)?
views:
892answers:
4Yes.
I would achieve this by doing two separate queries and inserting in to an array with their specified properties (eg. text color, id etc.), and then "binding" the combobox to the array.
Sorry, no code samples as I am not that good at c#, but this is how I would achieve the goal in my language of choice.
What i would do is combine them as one datasource, sorting it as you please, adding a property that indicates the color and then you could bind the text to one property and the color to another.
I think it is better to get the data into two datatables first, merge them as you please and then you can bind the final datatable to your combobox.
You can query from different datasource and dump it in a single collection type and bind to combobox.
Here is a sample code, you can do something similar to this using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<Item> items;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Let's say we are getting items from two different datasources and putting them in a same collection
items = new List<Item>();
//Getting pens from dataSource1
items.Add (new Pen("Parker",Color.Blue ));
items.Add(new Pen("Paper Mate", Color.Blue));
//Adding Books from dataSource2
items.Add(new Book("Programming in C", Color.Red));
items.Add(new Book("Design Patterns", Color.Red));
//Data binding
comboBox1.DataSource = items;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Color";
this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed; //Do not forget this
}
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
int index = e.Index;
Item item = comboBox1.Items[index] as Item ;
if (item.Color.Equals ( Color.Red))
e.Graphics.DrawString(item.Name, this.Font , Brushes.Red, new Point(e.Bounds.X, e.Bounds.Y));
else if (item.Color.Equals ( Color.Blue))
e.Graphics.DrawString(item.Name, this.Font, Brushes.Blue, new Point(e.Bounds.X, e.Bounds.Y));
else
e.Graphics.DrawString(item.Name, this.Font, Brushes.Black, new Point(e.Bounds.X, e.Bounds.Y));
}
}
public abstract class Item
{
string name;
Color color;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public Color Color
{
get
{
return color;
}
set
{
color = value;
}
}
}
public class Book:Item
{
public Book(string name, Color color){
this.Name = name;
this.Color = color;
}
}
public class Pen : Item
{
public Pen(string name, Color color){
this.Name = name;
this.Color = color;
}
}
}