I have few tables, using Entity Framework 6. My goal is to bind class table1 to ComboBox Value Member
ComboBox DataSource is:
ComboBoxBasicDB[] statType = new ComboBoxBasicDB[] {
new ComboBoxBasicDB { Text = "A1", Value = 0 },
new ComboBoxBasicDB { Text = "A2", Value = 1 },
new ComboBoxBasicDB { Text = "A3", Value = 2 },
new ComboBoxBasicDB { Text = "A4", Value = 4 },
new ComboBoxBasicDB { Text = "B12", Value = 12 },
new ComboBoxBasicDB { Text = "B13", Value = 13 },
new ComboBoxBasicDB { Text = "B14", Value = 14 }
};
statBS.DataSource = statType; // statBS == BindingSource, configured throught VS designer, comboBox.DataSource = statBS, comboBox.ValueMember = Value, comboBox.DisplayMember = Text
table1 contains property called ex. Value1 which contains one of these (0, 1, 2, 4, 12, 13, 14)
What am I trying to do is to load from DB row and use something like this on TextBox:
textBox.DataBindings.Add("Text", binding, "Name");
which works perfectly
I tried something like this:
comboBox.DataBindings.Add("SelectedValue", binding, "Value1");
but it not working, nothing is selected after query. textBox bind successfully
I used SelectedIndex but there is going one problem, and that is value above 7, because there are 7 items in statType not 14.
I hope you understand what am I trying to do :/
I thought I could do that throught comboBox.DataManager but its private
Thanks for any ideas.
So solution is custom implementation, in mentioned DataBindings change SelectedValue to SelectedItemValue
Implementation:
public class ComboBoxBasic : ComboBox
{
bool diffTextColor = false;
public ComboBoxBasic()
{
}
public object SelectedItemValue
{
get
{
return (SelectedItem as ComboBoxBasicDB).Value;
}
set
{
for(int i = 0; i < Items.Count; i++)
{
ComboBoxBasicDB item = Items[i] as ComboBoxBasicDB;
if(item.Value.ToString() == value.ToString())
{
SelectedIndex = i;
break;
}
}
}
}
public bool DifferentTextColor
{
get { return diffTextColor; }
set
{
diffTextColor = value;
if (diffTextColor)
{
DrawItem += ComboBoxBasic_DrawItem;
DrawMode = DrawMode.OwnerDrawFixed;
}
else
DrawItem -= ComboBoxBasic_DrawItem;
}
}
void ComboBoxBasic_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (e.State == DrawItemState.Focus)
e.DrawFocusRectangle();
Brush brush = new SolidBrush((sender as Control).ForeColor);
ComboBoxBasicDB item = (sender as ComboBoxBasic).Items[e.Index] as ComboBoxBasicDB;
if (item.ForeColor != Brushes.Black)
brush = item.ForeColor;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawString(item.Text, (sender as Control).Font, brush, e.Bounds.X, e.Bounds.Y);
}
}
Also there is custom DrawItem if its enabled by DifferentTextColor
Related
Im not sure im doing something fairly simple wrong. Im getting below plot when using the below code. I was expecting to get the B values in its own column like you would in excel.
EDIT: I have added my config in the post also, if there are some properties that im missing
/Thomas
BarDataset<double> _barDataSet3 = new BarDataset<double>
{
Label = "A",
BackgroundColor = ColorUtil.RandomColorString(),
BorderWidth = 0,
HoverBackgroundColor = ColorUtil.RandomColorString(),
HoverBorderColor = ColorUtil.RandomColorString(),
HoverBorderWidth = 1,
BorderColor = "#ffffff"
};
_barChartConfig.Data.Labels.AddRange(new[] { "A"});
_barDataSet3.Add(2.6);
_barChartConfig.Data.Datasets.Add(_barDataSet3);
BarDataset<double> _barDataSet4 = new BarDataset<double>
{
Label = "B",
BackgroundColor = ColorUtil.RandomColorString(),
BorderWidth = 0,
HoverBackgroundColor = ColorUtil.RandomColorString(),
HoverBorderColor = ColorUtil.RandomColorString(),
HoverBorderWidth = 1,
BorderColor = "#ffffff"
};
_barChartConfig.Data.Labels.AddRange(new[] { "B" });
_barDataSet4.Add(4.5);
_barChartConfig.Data.Datasets.Add(_barDataSet4);
EDIT: My config - is there a property that im missing?:
_barChartConfig = new BarConfig
{
Options = new BarOptions
{
Title = new OptionsTitle
{
Display = true,
Text = "Simple Bar Chart"
},
Scales = new BarScales
{
XAxes = new List<CartesianAxis>
{
new BarCategoryAxis
{
BarPercentage = 0.5,
BarThickness = BarThickness.Flex
}
},
YAxes = new List<CartesianAxis>
{
new BarLinearCartesianAxis
{
Ticks = new LinearCartesianTicks
{
BeginAtZero = true
}
}
}
}
}
};
I am returning my query value in array like,
public IEnumerable<ItemTable> SearchItem(string itemName)
{
return (from i in
_connection.Table<ItemTable>()
where i.ItemName.StartsWith(itemName)
select i).ToArray();
}
Can anyone tell me how to get this array value when i call this function means how to get this result to show on screen on label's text. Please Reply
Here is a sample;
public IEnumerable<ItemTable> SearchItem(string itemName)
{
return (from i in
_connection.Table<ItemTable>()
where i.ItemName.StartsWith(itemName)
select i).ToArray();
}
private string DisplayItemsInLabel(string itemName)
{
var searchedItems = this.SearchItem(itemName); // get items using above method that you have written already.
// get name and price
var displayableItems = searchedItems.Select(i => string.Format("Name :{0}, Price :{1}", i.Name, i.Price));
// create a formatted string using name and the price. so that we can display it in a label.
return string.Join(Environment.NewLine, displayableItems);
}
public LabelPage()
{
InitializeComponent();
var layout = new StackLayout { Padding = new Thickness(5, 10) };
this.Content = layout;
//display contents in a label
var label = new Label { Text = DisplayItemsInLabel("MyItem"), TextColor = Color.FromHex("#77d065"), FontSize = 20 };
layout.Children.Add(label);
}
I have a table with columns c1 .. c4 and with a row containing data such as
c1 c2 c3 c4
[CAN][YOU][HELP][ME]
Multiselect is on. When I get datagridview.SelectedCells then they will be in the list in order of when they were selected. E.g. I select HELP and then YOU the list will be HELP followed by YOU. However I need a list to show YOU,HELP because YOU is from a column before HELP. If I would select YOU,HELP,CAN in that order then the list should be CAN,YOU,HELP because CAN is in c1, YOU in c2 and HELP in c3.
How can I do this? Thank you for your help.
Chris
Hi here is the code. The order of the selected cell list depends on how you select them - e.g. start left to right or vice versa. As you can see from the code, I have found a workaround. The OrderBy idea is much more elegant but I believe it only works for Rows and not for cells.
private void attribute_treeview_DragDrop(object sender, DragEventArgs e)
{
// dropped item from either datagridview into treeview
if (e.Data.GetDataPresent(typeof(List<string>)))
{
// Determine which category the item was draged to
Point p = attribute_treeview.PointToClient(new Point(e.X, e.Y));
TreeNode destinationNode = attribute_treeview.GetNodeAt(p);
// sort selected cells based on position in productname
var selected_cells = e.Data.GetData(typeof(List<string>)) as List<string>;
SortedDictionary<int, string> orderedcellcontents = new SortedDictionary<int, string>();
ProductItem pitem = new ProductItem((BsonDocument)productlist.SelectedItems[0].Tag);
foreach (var element in selected_cells)
{
int pos = Array.IndexOf(pitem.tokens, element);
if (!orderedcellcontents.ContainsKey(pos))
orderedcellcontents.Add(pos, element);
}
if (PopulateTreeview(destinationNode, orderedcellcontents.Values.ToList<string>()))
{
dictionary_haschanged = true;
destinationNode.Expand();
}
}
I think this is much easier/cleaner/shorter.
datagridview.SelectedCells
.Cast<DataGridViewCell>()
.OrderBy(c=>c.ColumnIndex)
you can try using linq to order them on index
var ordered = datagridview.SelectedCells.OrderBy(c=>c.Index)
Edit 1: so the above doesn't seem to work. Below I've created a small forms app to test.
The app consists of a form with a datagridview on it, a button and a textbox.
Clicking the button will display the selectedcells in their correct order in the textbox.
See the button1_click event for the sorting.
Forms1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var data = new List<Data>();
data.Add(new Data { A = "CAN", B = "YOU", C = "HELP", D = "ME" });
data.Add(new Data { A = "CAN", B = "YOU", C = "HELP", D = "ME" });
data.Add(new Data { A = "CAN", B = "YOU", C = "HELP", D = "ME" });
data.Add(new Data { A = "CAN", B = "YOU", C = "HELP", D = "ME" });
dataGridView1.DataSource = data;
}
private void button1_Click(object sender, EventArgs e)
{
var selectedCells = dataGridView1.SelectedCells;
var array = new DataGridViewCell[selectedCells.Count];
selectedCells.CopyTo(array,0);
var sorted = array.OrderBy(c => c.ColumnIndex);
var s = string.Join(Environment.NewLine, sorted.Select(c => c.Value));
textBox1.Text = s;
}
}
public class Data
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
}
Copying the cells to a DataGridViewCell array will let you sort it on the index.
I would like to customize my list view to add some color depending on the label property.
If my amount label is > 0, I would like to set the color to green and if not to red.
How can I do that ?
// Create the list view
listView = new ListView
{
// Source of data items
ItemsSource = items,
// Define the template for displaying each item
ItemTemplate = new DataTemplate(() =>
{
Label noLabel = new Label();
noLabel.SetBinding(Label.TextProperty, "no");
Label orderDateLabel = new Label();
orderDateLabel.SetBinding(Label.TextProperty,
new Binding("orderDate") {Converter = new DateConverter()});
Label customerNameLabel = new Label();
customerNameLabel.SetBinding(Label.TextProperty, "customerName");
Label externalDocumentNoLabel = new Label();
externalDocumentNoLabel.SetBinding(Label.TextProperty, "externalDocumentNo");
Label amountLabel = new Label();
amountLabel.HorizontalTextAlignment = TextAlignment.End;
// Binding with converter
amountLabel.SetBinding(Label.TextProperty, new Binding("amount") {Converter = new AmountConverter()});
// Return an assembled view cell
return new ViewCell
{
View = new Grid
{
// Fill the grid with data and position
Children =
{
{
noLabel, 0, 0
},
{
orderDateLabel, 1, 0
},
{
customerNameLabel, 2, 0
},
{
externalDocumentNoLabel, 3, 0
},
{
amountLabel, 4, 0
}
}
}
};
})
};
If the amountLabel > 0 -> amoutLabel.TextColorProperty = Color.Green
Else amountLabel.TextColorProperty = Color.Red
I know I had to play around with the TextColorProperty but how to retrieve the Text property of the label ?
You bind it to the same data element as the text property, and use a converter to convert the value to a Color.
amountLabel.SetBinding(Label.TextColorProperty, new Binding("amount")
{ Converter = new AmountColorConverter() }
);
I am using Dotnet Highchart with MVC3
I am currently working with a diagram that looks like this:
I am trying to modify my code so I can change color on the bars depending on what number they have. I also wonder how I can remove the button "Snittbetyg" as you see can on the image.
This is my code:
public ActionResult OfficeStatistic()
{
{
Highcharts chart1 = new Highcharts("chart1")
.SetXAxis(new XAxis { Categories = new[] { "Ödmjukhet", "Engagemang", "Kompetens", "Lönsamhet" } })
.SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Betygskalan" } })
.SetSeries(new Series { Data = new Data(new object[] { 1, 8, 9, 6 }), Name = "Snittbetyg" })
.SetTitle(new Title { Text = "Örebro Statistik" })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column });
return View(chart1);
}
}
Any kind of help is appreciated.
Thanks in advance!
I haven't used Highchart but you can download examples from their codeplex page. It looks like both of your requirements can be achieved easily.
Remove the "Snittbetyg" button
Disable the legend:
.SetLegend(new Legend { Enabled = false });
Add Colours
For the series data use points instead of just the numbers:
Data data = new Data(new[]
{
new Point { Y = 1, Color = System.Drawing.Color.Red },
new Point { Y = 8, Color = System.Drawing.Color.Blue },
new Point { Y = 9, Color = System.Drawing.Color.Green },
new Point { Y = 6, Color = System.Drawing.Color.Black }
});
Highcharts chart1 = new Highcharts("chart1")
.SetXAxis(new XAxis { Categories = new[] { "Ödmjukhet", "Engagemang", "Kompetens", "Lönsamhet" } })
.SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Betygskalan" } })
.SetSeries(new Series { Data = data, Name = "Snittbetyg" })
.SetTitle(new Title { Text = "Örebro Statistik" })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetLegend(new Legend { Enabled = false });
There doesn't seem to be a built in way to make highchart automatically colour the bar based on the y-value. I believe you would have to pick the colour yourself, e.g:
private System.Drawing.Color GetBarColour(int value)
{
if (value < 5) return System.Drawing.Color.Red;
if (value > 7) return System.Drawing.Color.Green;
return System.Drawing.Color.Orange;
}
public ActionResult OfficeStatistic()
{
{
var dataItems = new[] {1, 8, 9, 6};
Data data = new Data(
dataItems.Select(y => new Point {Color = GetBarColour(y), Y = y}).ToArray()
);
Highcharts chart1 = new Highcharts("chart1")
.SetXAxis(new XAxis { Categories = new[] { "Ödmjukhet", "Engagemang", "Kompetens", "Lönsamhet" } })
.SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Betygskalan" } })
.SetSeries(new Series { Data = data, Name = "Snittbetyg" })
.SetTitle(new Title { Text = "Örebro Statistik" })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetLegend(new Legend { Enabled = false });
First, define a Tuple list first item is for color and second item point value
List<Tuple<string, Object>> dataItems = new List<Tuple<string, Object>>();
i am passing value with swtich it is not neccessary
SqlDataReader reader = myComm.ExecuteReader();
if (reader.HasRows)
{
string colorName ="";
while (reader.Read())
{
switch ((string)reader.GetValue(1))
{
case "Total Employee(s)":
colorName = "Blue";
break;
case "Present":
colorName = "Green";
break;
case "Late":
case"Absent":
case "During Less":
case "Early Going":
colorName = "Red";
break;
case "Leave":
colorName = "Orange";
break;
default:
colorName = "Gray";
break;
}
dataItems.Add(new Tuple<string, Object>(colorName, reader.GetValue(2)));
}
Now, Finally add Data into series object
new Series{
Name = "Employees",
Data = new Data(
dataItems.Select(y => new Point {
Color = System.Drawing.Color.FromName(y.Item1),
Y = (int)y.Item2 }).ToArray()
)
}