Setting GridView header filters - c#

I have a DevExpress gridview with a description column that has column header filters enabled. The problem is that having these filters enabled makes it so an entry is added to the drop down for every data item in the list which isn't really desirable because the entries are generally paragraphs of text. Instead I would like to restrict the options to just All, Blanks, and Non blanks but I haven't been able to find a clear example of how this might be accomplished. Thanks for the help!
ANSWER:
settings.HeaderFilterFillItems = (sender, e) =>
{
if (e.Column.FieldName == "Description")
{
e.Values.Clear();
e.AddShowAll();
e.Values.Insert(1, FilterValue.CreateShowBlanksValue(e.Column, "(Blanks)"));
e.Values.Insert(2, FilterValue.CreateShowNonBlanksValue(e.Column, "(Non Blanks)"));
}
};

This question is similar than yours https://www.devexpress.com/Support/Center/Question/Details/Q477323/gridview-how-to-customize-header-filter-items
And here in the view you have the custom filter items, using settings.HeaderFilterFillItems https://demos.devexpress.com/MVCxGridViewDemos/Filtering/Filtering
#Html.DevExpress().GridView(
settings => {
settings.Name = "gvFiltering";
settings.CallbackRouteValues = new { Controller = "Filtering", Action = "FilteringPartial", EnableCheckedListMode = ViewBag.EnableCheckedListMode };
settings.Width = Unit.Percentage(100);
settings.Columns.Add("CompanyName");
settings.Columns.Add("Country");
settings.Columns.Add("City");
settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
settings.Columns.Add("Quantity");
settings.Columns.Add("Discount").PropertiesEdit.DisplayFormatString = "p0";
settings.Columns.Add(column => {
column.FieldName = "Total";
column.PropertiesEdit.DisplayFormatString = "c";
column.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
column.UnboundExpression = "UnitPrice * Quantity * (1 - Discount)";
});
settings.Settings.ShowHeaderFilterButton = true;
settings.SettingsPopup.HeaderFilter.Height = 200;
var headerFilterMode = ViewBag.EnableCheckedListMode ? GridHeaderFilterMode.CheckedList : GridHeaderFilterMode.List;
foreach(GridViewDataColumn column in settings.Columns)
column.SettingsHeaderFilter.Mode = headerFilterMode;
settings.HeaderFilterFillItems = (sender, e) => {
ASPxGridView grid = (ASPxGridView)sender;
if(e.Column.FieldName == "Total") {
e.Values.Clear();
if(e.Column.SettingsHeaderFilter.Mode == GridHeaderFilterMode.List)
e.AddShowAll();
int step = 100;
for(int i = 0; i < 10; i++) {
double start = step * i;
double end = start + step - 0.01;
e.AddValue(string.Format("from {0:c} to {1:c}", start, end), string.Empty, string.Format("[Total] >= {0} and [Total] <= {1}", start, end));
}
e.AddValue(string.Format("> {0:c}", 1000), string.Empty, "[Total] > 1000");
} else if(e.Column.FieldName == "Quantity") {
int max = 0;
for(int i = 0; i < e.Values.Count; i++) {
int value;
if(!int.TryParse(e.Values[i].Value, out value))
continue;
if(value > max)
max = value;
}
e.Values.Clear();
if(e.Column.SettingsHeaderFilter.Mode == GridHeaderFilterMode.List)
e.AddShowAll();
int step = 10;
for(int i = 0; i < max / step + 1; i++) {
int start = step * i;
int end = start + step - 1;
e.AddValue(string.Format("from {0} to {1}", start, end), string.Empty, string.Format("[Quantity] >= {0} and [Quantity] <= {1}", start, end));
}
}
};
}).Bind(Model).GetHtml()

Related

How can I append values in list without changing previous values

I have class in C# -
public class Availability
{
public ushort RegionId {get;set;}
}
Then , I have a method GetListOfClassesAsPerIterations(Availability xiAvailability)
I have List in this method where I want to append different values of RegionId.
Eg. First 100 elements in List with RegionId=1500 , next 100 elements with RegionId=1400
But what is happening is , when I add first 100 elements in list with RegionId=1500 , and then try to add next 100 elements in list with RegionId=1400 , all the items in List becomes with RegionId=1400.
I have written code for it as -
var lstAvailability = List<Availability>
for (int i = 0; i < 100; i++)
{
xiAvailability.RegionId = 1500;
lstAvailability.Add(xiAvailability);
}
for (int i = 0; i < 100; i++)
{
xiAvailability.RegionId = 1400;
lstAvailability.Add(xiAvailability);
}
Here I can see all the 200 elements with RegionId as 1400.
But instead , I was expecting first 100 to be with 1500 and next 100 to be with 1400.
What could be the alternative?
This is because you are putting 200 references to the same object in the list. If you want to have 200 different objects, then you need to do something like this:
var lstAvailability = new List<Availability>();
for (int i = 0; i < 200; i++)
{
var xiAvailability = new Availability();
if (i < 100)
xiAvailability.RegionId = 1400;
else
xiAvailability.RegionId = 1500;
lstAvailability.Add(xiAvailability);
}
If you need to have 100 references to 2 objects, then do this
var lstAvailability = new List<Availability>();
var xiAvailability = new Availability() { RegionId=1400 };
for (int i = 0; i < 200; i++)
{
if (i == 100)
xiAvailability = new Availability() { RegionId = 1500 };
lstAvailability.Add(xiAvailability);
}
Object in the list is a reference to the actual object. Hence, you're seeing the latest value of 1400 for RegionId.
You can try the below,
var xiAvailability1500 = new Availability();
xiAvailability1500.RegionId = 1500;
var xiAvailability1400 = new Availability();
xiAvailability1400.RegionId = 1400;
var lstAvailability = List<Availability>();
for (int i = 0; i < 200; i++)
{
if (i < 100)
lstAvailability.Add(xiAvailability1500);
else
lstAvailability.Add(xiAvailability1400);
}
Here is another alternative way:
var lstAvailability = List<Availability>
int count = 0;
for (int i = 0; i < 200; i++)
{
if(count => 0 && count <= 100)
{
xiAvailability.RegionId = 1500;
lstAvailability.Add(xiAvailability);
}
if (count => 100)
{
xiAvailability.RegionId = 1400;
lstAvailability.Add(xiAvailability);
}
count = count + 1;
}

OpenPop Pop3 winform MaxMessage c#

I have problem with messages in mail program. If i have 20 mails it's ok load pretty fast but if i have 700 it's a problem it take a long of time. I can go make coffe and back. How I can set max messages to 50.
try
{
client.Connect(comboBox5.Text, 995, true);
client.Authenticate(textBox6.Text, textBox5.Text, OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
int count = client.GetMessageCount();
string htmlContained = "";
for (int i = count; i >= 1; i -= 1)
{
OpenPop.Mime.Message message = client.GetMessage(i);
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
if (html != null)
{
htmlContained = html.GetBodyAsText();
} else
{
html = message.FindFirstPlainTextVersion();
if (html != null)
{
htmlContained = html.GetBodyAsText();
}
}
string name = message.Headers.Subject;
if (name == "")
{
name = "Usigned";
}
dt.Rows.Add(new object[] { name.ToString(), message.Headers.From.DisplayName, message.Headers.From.Address, htmlContained, message.Headers.DateSent });
}
client.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
for (int i = count; i >= 1; i -= 1)
->
for (int i = 0; i < count && i < 50; i++)
Or (less redable according to me):
for (int i = count; i >= 1; && (count - i) < 50; i -= 1)
You may also want to implement paging:
var pageSize = 50;
var startPage = x;
for (int i = x * pageSize; i < count && i < pageSize; i++)

ATM program, can't figure out how to break down withdraw amount

First off yes, This is a homework assignment, I've been struggling with it for 3 days, and I can't figure it out.
Basically the problem is to take a decimal amount entered by the user in a text box, I then need to take that number and break it down into currency denominations, $50, $20, $10, $5, $1 and if the amount has a decimal then into
$.25, $.10, $.05, $.01.
And I need to break this down in the lowest amount of denominations possible, for example $100 would be broken down into 2 $50 bills.
Here is what I have so far.
private void btnDispense_Click(object sender, EventArgs e)
{
decimal i;
i = decimal.Parse(txtAmountReq.Text);
decimal totalAmount = Convert.ToDecimal(txtAmountReq);
int[] denomBills = { 50, 20, 10, 5, 1 };
int[] numberOfBills = new int[5];
decimal[] denomCoins = { .25m, .10m, .05m, .01m };
int[] numberOfCoins = new int[4];
//For loop for amount of bills
for (numberOfBills[0] = 0; totalAmount >= 50; numberOfBills[0]++)
{
totalAmount = totalAmount - 50;
}
for (numberOfBills[1] = 0; totalAmount < 20; numberOfBills[1]++)
{
totalAmount = totalAmount - 20;
}
for (numberOfBills[2] = 0; totalAmount < 10; numberOfBills[2]++)
{
totalAmount = totalAmount - 10;
}
for (numberOfBills[3] = 0; totalAmount < 5; numberOfBills[3]++)
{
totalAmount = totalAmount - 5;
}
for (numberOfBills[4] = 0; totalAmount <= 0; numberOfBills[4]++)
{
totalAmount = totalAmount - 1;
}
//For loop for the amount of coins
for (numberOfCoins[0] = 0; totalAmount >= .25m; numberOfBills[0]++)
{
totalAmount = totalAmount - .25m;
}
for (numberOfBills[1] = 0; totalAmount < .10m; numberOfBills[1]++)
{
totalAmount = totalAmount - .10m;
}
for (numberOfBills[2] = 0; totalAmount < .05m; numberOfBills[2]++)
{
totalAmount = totalAmount - .05m;
}
for (numberOfBills[3] = 0; totalAmount < .01m; numberOfBills[3]++)
{
totalAmount = totalAmount - .01m;
}
txt50.Text = Convert.ToString(numberOfBills[0]);
txt20.Text = Convert.ToString(numberOfBills[1]);
txt10.Text = Convert.ToString(numberOfBills[2]);
txt5.Text = Convert.ToString(numberOfBills[3]);
txt1.Text = Convert.ToString(numberOfBills[4]);
txtQuarter.Text = Convert.ToString(numberOfCoins[0]);
txtDime.Text = Convert.ToString(numberOfCoins[1]);
txtNickel.Text = Convert.ToString(numberOfCoins[2]);
txtPenny.Text = Convert.ToString(numberOfCoins[3]);
}
Any help would be greatly appreciated.
This is very famous knapsack type problem.You might want to start exploring from here : https://en.wikipedia.org/wiki/Change-making_problem
The best way to address this problem is to find all possible combinations of change and then find the optimal solution.
Below is the code by karamana I found on codeproject.com :
//find all the combinations
private void findAllCombinationsRecursive(String tsoln,
int startIx,
int remainingTarget,
CoinChangeAnswer answer) {
for(int i=startIx; i<answer.denoms.length ;i++) {
int temp = remainingTarget - answer.denoms[i];
String tempSoln = tsoln + "" + answer.denoms[i]+ ",";
if(temp < 0) {
break;
}
if(temp == 0) {
// reached the answer hence quit from the loop
answer.allPossibleChanges.add(tempSoln);
break;
}
else {
// target not reached, try the solution recursively with the
// current denomination as the start point.
findAllCombinationsRecursive(tempSoln, i, temp, answer);
}
}
}
in order to find optimum solution :
public CoinChangeAnswer findOptimalChange(int target, int[] denoms) {
CoinChangeAnswer soln = new CoinChangeAnswer(target,denoms);
StringBuilder sb = new StringBuilder();
// initialize the solution structure
for(int i=0; i<soln.OPT[0].length ; i++) {
soln.OPT[0][i] = i;
soln.optimalChange[0][i] = sb.toString();
sb.append(denoms[0]+" ");
}
// Read through the following for more details on the explanation
// of the algorithm.
// http://condor.depaul.edu/~rjohnson/algorithm/coins.pdf
for(int i=1 ; i<denoms.length ; i++) {
for(int j=0; j<target+1 ; j++) {
int value = j;
int targetWithPrevDenomiation = soln.OPT[i-1][j];
int ix = (value) - denoms[i];
if( ix>=0 && (denoms[i] <= value )) {
int x2 = denoms[i] + soln.OPT[i][ix];
if(x2 <= target && (1+soln.OPT[i][ix] < targetWithPrevDenomiation)) {
String temp = soln.optimalChange[i][ix] + denoms[i] + " ";
soln.optimalChange[i][j] = temp;
soln.OPT[i][j] = 1 + soln.OPT[i][ix];
} else {
soln.optimalChange[i][j] = soln.optimalChange[i-1][j]+ " ";
soln.OPT[i][j] = targetWithPrevDenomiation;
}
} else {
soln.optimalChange[i][j] = soln.optimalChange[i-1][j];
soln.OPT[i][j] = targetWithPrevDenomiation;
}
}
}
return soln;
}
Link to the original code here

how to add a row to the next page of datagridview

I have a list that has some records which is bind with a datagridview.This list contains some properties like pageno , pagebreak, rowno etc. Now I am adding some new row to the Datagridview, when the grid is at page no 1 ,the row which i add inserted at right location but when i move to second page or third page of Datagridview and add a new row it insert at very top of the datagridview. I have done some code for inserting the row at right location and i am also attaching a image for better understanding my problem..
foreach (RowType Itemm in box9.SelectedItems)
{
FRReportRow newrow = new FRReportRow();
name = Itemm.TypeName;//box9.Text.ToString();
var ro = FixedSpecial.Where(x => x.TypeName == name).SingleOrDefault();
newrow.Item = name;
newrow.RowType = ro.IndexType;
if (newrow.RowType == 7)
PageBreaker = 1;
newrow.RowInfo = GetRowInfo(newrow.RowType);
if (newrow.RowInfo == string.Empty)
{
newrow.RowInfo = M3.FWL.UI.LayoutUc.EnumRowInfo.F.ToString();
}
ListRow.Add(newrow);
//To manage items added with page breaker
if (PageBreaker == 1 && newrow.RowType != 7)
AfterPageBreak.Add(newrow);
}
}
int prevpage;
List<FRReportRow> ListToBeAdded = new List<FRReportRow>();
if (IsValidationRequired)
ListToBeAdded = IsMultipleItemAlreadyExist(ListRow);
else
ListToBeAdded = ListRow;
if (ListToBeAdded.Count > 0)
{
groupBox1.Enabled = true;
var pagebreak = lstnewRow.Where(x => x.RowType == 7).ToList();
ListToBeAdded.ForEach(x => x.Pageno = Convert.ToInt32(nudpage.Value));
//Check Items after pagebreaker to change page no
if (AfterPageBreak.Count > 0)
{
foreach (FRReportRow item in ListToBeAdded)
{
int count = AfterPageBreak.Where(x => x == item).Count();
if (count > 0)
item.Pageno = item.Pageno + 1;
}
}
int rowNo = 0;
if (!PageBreakExist)
rowNo = gvlayoutload.SelectedRows[0].Index;//gvlayoutload.Rows.Count;
else
PageBreakExist = false;
int AfterPageRowNo = 0;
foreach (FRReportRow item in ListToBeAdded)
{
#region Determine the Rowno of the Item
int count = 0;
if (AfterPageBreak.Count > 0)
{
count = AfterPageBreak.Where(x => x == item).Count();
if (count > 0)
AfterPageRowNo = AfterPageRowNo + 1;
}
if (count > 0) //When item added after pagebreak in one go.
rowNo = AfterPageRowNo;
else
rowNo = rowNo + 1;
#endregion
item.RowNo = rowNo;
item.size = 8;
item.AlignText = 0;
item.AlignData = 2;
item.Indent = 0.1;
item.Loadas = 0;
item.fNegativeFormat = 0;
item.Format = 0;
// lstnewRow.Add(item);
mRowIndex = gvlayoutload.SelectedRows[0].Index;
lstnewRow.Add(item);
else if (mRowIndex >= 0 && mRowIndex < lstnewRow.Count) // other than first and last row
{
lstnewRow.Insert(mRowIndex + 1, item);
}
for (int i = 0; i < lstnewRow.Count; i++)
{
lstnewRow[i].RowNo = i + 1;
//lstnewRow[i].isUpdated = true;
}
}
if (AfterPageBreak.Count > 0)
{
pagebreak = lstnewRow.Where(x => x.RowType == 7).ToList();
PageBreaker = 0;
}
var newlst = lstnewRow.ToList();
this.fRReportRowBindingSource.DataSource = newlst;

Silverlight Toolkit chart control doesnt always show X axis values

I have an Silverlight 5 application which is using the Silverlight Toolkit. Now, the Silverlight Toolkit chart control doesnt always show X axis values when there is only one result in the resultset that returns from my webserivce.
The first image shows that my chart is loaded properly when selecting a big enough resultset.
The second image shows that it doesn't when the resultset exists of 1 item.
This is my implementation:
TimeSpan monthSpan = TimeSpan.FromDays(30.0);
TimeSpan daySpan = TimeSpan.FromDays(1.0);
TimeSpan hourSpan = TimeSpan.FromHours(1.0);
foreach (TagValueResult res in e.NewItems)
{
if (res != null)
{
LineSeries lineSeries = new LineSeries()
{
Title = string.Format("{0}" + Environment.NewLine + " {2} ({1})", res.Name, res.Attributes["UOM"], res.Attributes["Description"]),
ItemsSource = res.Values,
DependentValueBinding = new System.Windows.Data.Binding("Value"),
IndependentValueBinding = new System.Windows.Data.Binding("Key"),
Tag = res,
PolylineStyle = Resources["thinLineStyle"] as Style,
//DataPointStyle = Resources["dataPointStyle"] as Style
};
if (res.Values.Any() && chart.Series.Any() == false)
{
TimeSpan graphSpan = res.Values.ToList().Last().Key - res.Values.ToList().First().Key;
lineSeries.IndependentAxis = new DateTimeAxis
{
Minimum = res.Values.ToList().First().Key,
Maximum = res.Values.ToList().Last().Key,
Interval = 1,
Orientation = AxisOrientation.X,
Location = AxisLocation.Bottom
};
if (graphSpan > monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 5;
}
else if (graphSpan > daySpan && graphSpan < monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan > hourSpan && graphSpan < daySpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Hours;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan < hourSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Minutes;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 15;
}
else
{
//sometimes all comparisons fail, just back up to a safe interval of 1 day.
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
}
chart.Series.Add(lineSeries);
}
}
Do you have any idea's? I'm out of possible solutions.
A collection with one item will have incorrect behavior in several places of your code.
Here graphSpan will equal zero:
TimeSpan graphSpan = res.Values.ToList().Last().Key - res.Values.ToList().First().Key;
And here Maximum and Minimum will be the same:
lineSeries.IndependentAxis = new DateTimeAxis
{
Minimum = res.Values.ToList().First().Key,
Maximum = res.Values.ToList().Last().Key,
I suggest that you add another if-block and construct a different axis for the special case when the collection has only 1 item.
var values = res.Values.ToList();
TimeSpan graphSpan = values.Last().Key - values.First().Key;
if (graphSpan == TimeSpan.Zero)
{
lineSeries.IndependentAxis = new DateTimeAxis
{
Orientation = AxisOrientation.X,
Location = AxisLocation.Bottom
};
}
else
{
lineSeries.IndependentAxis = new DateTimeAxis
{
Minimum = values.First().Key,
Maximum = values.Last().Key,
Orientation = AxisOrientation.X,
Location = AxisLocation.Bottom
};
if (graphSpan > monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 5;
}
else if (graphSpan > daySpan && graphSpan < monthSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan > hourSpan && graphSpan < daySpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Hours;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
else if (graphSpan < hourSpan)
{
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Minutes;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 15;
}
else
{
//sometimes all comparisons fail, just back up to a safe interval of 1 day.
((DateTimeAxis)lineSeries.IndependentAxis).IntervalType = DateTimeIntervalType.Days;
((DateTimeAxis)lineSeries.IndependentAxis).Interval = 1;
}
}

Categories

Resources