Specific row withing a DataTable - asp.net

I have a data table which has a "Total" column. I want to be able to get a specific rows "Total" not all rows.
public void maxValue()
{
string pass = (String)Session["name"];
DataTable table = (DataTable)Session["CocaCola"];
int total = table.AsEnumerable().Sum(r => r.Field<int>("Total"));
int totalAllowed = table.AsEnumerable().Sum(r => r.Field<Int32>("Total Allowed"));
if (total >= totalAllowed)
{
Label1.Text = "Total value exceeded the maximum of " + totalAllowed;
}
else if (total < totalAllowed)
{
Label1.Text = "Total value which is allowed :" + totalAllowed;
}
if (pass.Equals("Low"))
{
Label1.Text = "You are not allowed any assets at this Stage";
//SNS.Checked = false;
//TT.Checked = false;
//Music.Checked = false;
//SNS.Enabled = false;
//TT.Enabled = false;
//Music.Enabled = false;
}
}
As you can see my method works but add the column up which i dont want to do. How would i go about changing it?

You can do it this way
int yourTargetindex = 0; //Change this to get the value of your target element
int total =(from row in table.AsEnumerable()
select row.Field<int>("Total")).ElementAt(yourTargetindex);
//This will return the first value of "total" in the DataTable

You don't have to use linq. DataTable has built-in methods for this kind of operations:
var selectedTotal = table.Compute("sum(Total)", "columnX == 'x'");
This tell the table to calculate the sum of all Total cells in rows where columnX has the specified value.
Of course you can use linq. You would need to add a Where() before you calculate the sum.

Related

DataGrid gets the value of a row and column

I want to get the value of a certain cell in the DataGrid of syncfusion.
like this:
<dataGrid:SfDataGrid x:Name="sfDataGrid">
</dataGrid:SfDataGrid>
C#:
Sfdatagrid\[i,j\] is useless.
How do I get the value of this cell.
https://help.syncfusion.com/winui/datagrid/overview The document
In this official document, I didn't find out how to get the value of this cell according to the index of rows and columns.
I want to get the value of this cell according to the index of the row and column.
Column A
Column B
Cell 1
Cell 2
Cell 3
Cell 4
For example, I want to get the value of this cell according to the index of the row and column.
How should I write code in c#
Your requirement to get the value of this cell according to the index of the row and column in SfDataGrid can be achieved by using View.GetPropertyAccessProvider.GetValue method in SfDatGrid. Please refer the below code snippet,
private void OnGetCellValueClicked(object sender, RoutedEventArgs e)
{
// Get the cell value for RowIndex = 5 and ColumnIndex = 2
int rowIndex = 5;
int columnIndex = dataGrid.ResolveToGridVisibleColumnIndex(2);
object record = null;
if (columnIndex < 0)
return;
var provider = this.dataGrid.View.GetPropertyAccessProvider();
var mappingName = dataGrid.Columns[columnIndex].MappingName;
var recordIndex = this.dataGrid.ResolveToRecordIndex(rowIndex);
if (this.dataGrid.View.TopLevelGroup != null)
{
var displayElement = this.dataGrid.View.TopLevelGroup.DisplayElements[recordIndex];
if (displayElement == null)
return;
if (displayElement is RecordEntry)
record = ((RecordEntry)displayElement).Data;
}
else
{
record = this.dataGrid.View.Records[recordIndex].Data;
if (record == null)
return;
}
var cellValue = provider.GetValue(record, mappingName);
//here display the cell value for RowIndex = 5 and ColumnIndex = 2
if (cellValue != null)
txtGetCellValue.Text = cellValue.ToString();
}

DataTable: Check a column for existing value

I have two DataTables, DataTable1 sends some of its values to DataTable2. What I want to do is if DataTable1 values already exists in DataTable2, the values will not add to DataTable2.
I have here values from DataTable1
protected void ASPxGridView1_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
if (e.ButtonID != "ADD") return;
int id = e.VisibleIndex
int DeliveredQty = Convert.ToInt32(ASPxGridView1.GetRowValues(id, "Delivered Qty"));
int InventoryID = Convert.ToInt32(ASPxGridView1.GetRowValues(id, "InventoryID"));
Now I want to check the DataTable2 values if there's an existing InventoryID in the rows.
This is what I ended up with
int id = InventoryID;
DataTable dt = DataTable2;
DataRow[] dr = dt.Select(id.ToString());
if (dr == null)
{
"if it does not exist, values will be addded"
}
else
{
"prompt user that values exist"
}
What's the correct way to do this?
You can use Linq to check for a value in a DataTable column
bool valueExists = dt.AsEnumerable().Any(x => x.Field<string>("ColumnName") == "abcd");

Count number of rows in DataTable that meet some criteria

DataTable dt = GetDataTable();
if(field=="TaskId")
{
string value = ((e.Item as GridFilteringItem)[field] as GridTableCell).Column.CurrentFilterValue
int VALUE = Int32.Parse(value);
int numberOfRecords = dt.Select("TaskId = VALUE").Length;
I want to count the number of rows in a DataTable that have a TaskId == value.
This code is throwing an error saying no column found TaskId[value].
Replace this line
int numberOfRecords = dt.Select("TaskId = VALUE").Length;
WITH
int numberOfRecords = dt.Select("TaskId = " + VALUE).Length;
you passed VALUE within ("")
You could use a simple for loop to iterate each row, looking at the TaskId field of each row. If it matches the criteria, increase a counter.
string value = ((e.Item as GridFilteringItem)[field] as GridTableCell).Column.CurrentFilterValue
int count = 0;
for(int i = 0; i < dt.Rows.Count; i++)
{
if(dt.Rows[i]["TaskId"].ToString() == value)
{
count++;
}
}
Either that or you could use LINQ as well. The rows variable will hold a collection of DataRows that meet your criteria.
var rows = from row in dt.AsEnumerable()
where row.Field<string>("TaskId") == value
select row;
int count = rows.Count<DataRow>();

XtraGrid AutoFilterRow custom range filtering

I'm trying to improve the AutoFilterRow functionality for one of my columns. The column will always consist of a string that represents a range of values like this: "num1 - num2". I would like to allow end users to type a value into the cell in the AutoFilterRow and in this particular column and the rows whose sections have a range that includes the number they typed. For instance, if I had 3 rows and each of their section attributes were the following: "1 - 4", "1 - 6", and "4 - 6", and a user types "3" into the AutoFilterRow cell for this column, I would expect the rows containing "1 - 4" and "1 - 6".
I have already overwritten the CreateAutoFilterCriterion in MyGridView to allow for additional operators as suggested in several examples found on this site:
protected override CriteriaOperator CreateAutoFilterCriterion(GridColumn column, AutoFilterCondition condition, object _value, string strVal)
{
if ((column.ColumnType == typeof(double) || column.ColumnType == typeof(float) || column.ColumnType == typeof(int)) && strVal.Length > 0)
{
BinaryOperatorType type = BinaryOperatorType.Equal;
string operand = string.Empty;
if (strVal.Length > 1)
{
operand = strVal.Substring(0, 2);
if (operand.Equals(">="))
type = BinaryOperatorType.GreaterOrEqual;
else if (operand.Equals("<="))
type = BinaryOperatorType.LessOrEqual;
else if (operand.Equals("<>"))
type = BinaryOperatorType.NotEqual;
}
if (type == BinaryOperatorType.Equal)
{
operand = strVal.Substring(0, 1);
if (operand.Equals(">"))
type = BinaryOperatorType.Greater;
else if (operand.Equals("<"))
type = BinaryOperatorType.Less;
else if (operand.Equals("!") || operand.Equals("~"))
type = BinaryOperatorType.NotEqual;
}
if (type != BinaryOperatorType.Equal)
{
string val = strVal.Replace(operand, string.Empty);
try
{
if (!val.IsEmpty())
{
if (column.ColumnType == typeof(double))
{
var num = Double.Parse(val, NumberStyles.Number, column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, num, type);
}
if (column.ColumnType == typeof(float))
{
var num = float.Parse(val, NumberStyles.Number, column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, num, type);
}
else
{
var num = int.Parse(val, NumberStyles.Number, column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, num, type);
}
}
// DateTime example:
// DateTime dt = DateTime.ParseExact(val, "d", column.RealColumnEdit.EditFormat.Format);
// return new BinaryOperator(column.FieldName, dt, type);
}
catch
{
return null;
}
}
}
//
// HERE IS WHERE I WANT TO ADD THE FUNCTIONALITY I'M SPEAKING OF
//
else if (column.FieldName == "SectionDisplayUnits")
{
try
{
if (!strVal.IsEmpty())
{
}
}
catch
{
return null;
}
}
return base.CreateAutoFilterCriterion(column, condition, _value, strVal);
}
How would I go about doing that? I figure I want to split each string with a call to Split(...) like this: cellString.Split(' - '). Then I would parse each string returned from the call to Split(...) into a number so that I could use inequality operators. But I'm just not sure how to go about doing this. Can I get some help? Thanks!
Update:
Please take a look here for a more in-depth discussion on this matter with myself and a knowledgeable DevExpress representative. I received a lot of help and I wanted to share this knowledge with whoever needs similar assistance. Here is the link.
Using C#, you would split the value into two parts, convert them to the number, and compare the value entered by the user with both values to ensure that it is greater or equal the first part and less or equal the second part.
In Criteria Language, the same functionality can be created using Function Operators. However, the expression will be a bit complex. Please try the following. It will work only if the format of values in the SectionDisplayUnits column is fixed, and the value always consists of two numbers delimited by "-".
string rangeDelimiter = "-";
return CriteriaOperator.Parse("toint(trim(substring(SectionDisplayUnits, 0, charindex(?, SectionDisplayUnits)))) <= ? && toint(trim(substring(SectionDisplayUnits, charindex(?, SectionDisplayUnits) + 1, len(SectionDisplayUnits) - charIndex(?, SectionDisplayUnits) - 1))) >= ?", rangeDelimiter, _value, rangeDelimiter, rangeDelimiter, _value);

specific distance between columns of drop down list

i like to have 2 columns in my drop down list with specific distance between 2 columns, so i have added below code but columns are not align with my code.
var query = from p in _DataContext.tblDocuments
orderby p.DocumentNo
select new
{
Doctitle = p.DocumentNo+' '+' '+"|"+' '+p.TITLE,
DocId = p.DocId
};
ddlProjectDocument.DataSource = query;
ddlProjectDocument.DataValueField = "DocId";
ddlProjectDocument.DataTextField = "Doctitle";
ddlProjectDocument.DataBind();
please help how i can have 2 columns with normal view and good align.
The alignment will depend on the length of the value in the field of your table. One way to do it would be to get the size of the largest entry in your table and make sure that all entries are that wide. Here is something you can try.
<asp:DropDownList ID="ddlStack" runat="server" OnLoad="ddlStack_Load" />
and in the source code for ddl load event:
protected void ddlStack_Load(object sender, EventArgs e)
{
var all = from o in _DataContext.tblDocuments
orderby o.DocumentNo
select o;
int maxs = 0;
foreach (tblDocuments v in all)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocuments vv in all)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs + 2; i++)
{
doctitle += '_';
}
doctitle += " | ";
doctitle += vv.DocID;
ddlStack.Items.Add(new ListItem(doctitle, vv.vendorID.ToString()));
}
}
You can try either from the below two methods:
1). select new
{
Doctitle = p.DocumentNo+" "+"|"+" "+p.TITLE,
DocId = p.DocId
};
2).
select new
{
Doctitle =Concat(p.DocumentNo,p.TITLE),
DocId = p.DocId
};

Resources