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>();
Related
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();
}
I have a datatable, then I have all the column names of the datatable as checkbox, I want to display only those column records, for which user selected from the checkbox:
Below is the code, but I am not getting the desired result
var values = "";
string clmnm = "";
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected)
{
values += interestedIN.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
string[] words = values.Split(',');
DataTable dt = new DataTable();
dt = (DataTable)Session["dataset"];
DataTable dt1 = new DataTable();
foreach (string word in words)
{
dt1.Columns.Add(word, typeof(string));
if (clmnm == string.Empty)
{
clmnm = word.Trim();
}
else
{
clmnm += "," +word.Trim();
}
}
foreach (DataRow dr in dt.Rows)
{
string[] split = clmnm.Split(',');
int j =0;
string str = "";
string str2 = "";
while( j < split.Length)
{
str = split[j].ToString();
if (str2 == string.Empty)
{
str2 = "dr[\""+str.ToString()+"\"]";
}
else
{
str2 += "," + "dr[\""+str.ToString()+"\"]";
}
j+=1;
}
dt1.Rows.Add(str2);
}
then I am trying to export the result as an excel sheet: but getting the below excel sheet:
There is a lot of changes to be done to your code. Lets begin with selected columns from CheckBoxList. Try using List or Arrays to store which columns that user wants. Like
List<string> columns = new List<string>();
Then store the selected columns into the columns list. Then you need to add columns to your new DataTable dt1. As,
DataTable dt1 = new DataTable();
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected) //If user selected this columns checkbox.
{
columns.Add(interestedIN.Items[i].Text.Trim()); //Storing values to List.
dt1.Columns.Add(interestedIN.Items[i].Text.Trim()); //Adding columns to the DataTable.
}
}
Then you can loop through your original DataTable dt and store the values as below.
foreach (DataRow dr in dt.Rows)
{
DataRow dr1 = dt1.NewRow(); // Create new row which should have identical structure for inserting.
foreach(string col in columns)
{
dr1(col) = dr(col);
}
dt1.Rows.Add(dr1); //Add the row with the contents to the table.
}
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
};
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.
I have dynamically created textbox in asp.net. Now i am extracting the values through following code.
string[] sublist = new string[] { };
int[] maxmarkslist = new int[] { };
int i;
for (i = 0; i < Convert.ToInt32(Label15.Text); i++)
{
string sub = "subject" + i;
string marks = "maxmarks" + i;
TextBox subject = (TextBox)PlaceHolder1.FindControl(sub);
TextBox maxmarks = (TextBox)PlaceHolder1.FindControl(marks);
sublist[i] = subject.Text;
maxmarkslist[i] = Convert.ToInt32(maxmarks.Text);
}
But I getting error "Index was outside the bounds of the array" for the below two lines:
sublist[i] = subject.Text;
maxmarkslist[i] = Convert.ToInt32(maxmarks.Text);
When I debugged it, values are coming in subject.Text and maxmarks.Text but not going to array.
Did I define the array in a wrong way?
You define both the arrays as empty arrays. So you will get index out of bound erros if you try to index into those.
Arrays are not dynamically expanding. If you want that, use a collection type and may be later convert to an array.
Try this:
int length = Convert.ToInt32(Label15.Text);
string[] sublist = new string[length-1];
int[] maxmarkslist = new int[length-1];
for (int i = 0; i < length; i++)
{
string sub = "subject" + i;
string marks = "maxmarks" + i;
TextBox subject = (TextBox)PlaceHolder1.FindControl(sub);
TextBox maxmarks = (TextBox)PlaceHolder1.FindControl(marks);
sublist[i] = subject.Text;
maxmarkslist[i] = Convert.ToInt32(maxmarks.Text);
}
Or here is how to do this with a collection (List) type:
int length = Convert.ToInt32(Label15.Text);
List<string> sublist1 = new List<string>();
List<int> maxmarkslist1 = new List<int>();
for (int i = 0; i < Convert.ToInt32(Label15.Text); i++)
{
string sub = "subject" + i;
string marks = "maxmarks" + i;
TextBox subject = (TextBox)PlaceHolder1.FindControl(sub);
TextBox maxmarks = (TextBox)PlaceHolder1.FindControl(marks);
sublist1.Add(subject.Text);
maxmarkslist1.Add(Convert.ToInt32(maxmarks.Text));
}
string[] sublist = sublist1.ToArray();
int[] maxmarkslist = maxmarkslist1.ToArray();
Note with collections you dont have to specify the size upfront. But keep adding items to it as it can expand as needed. But arrays can not do this.
Your string[] sublist = new string[] { }; is a shortcut method where you create and initialize the array. In that you don't have to specify the size, but compiler will count the elements between {} and set the size appropriately. In your case since there are no elements inside {} it will create an empty array.
string[] sublist = new string[100];
int[] maxmarkslist = new int[100];
Put this..replace 100 with the max possible value of your loop...but this is not a good practice...will come back to this thread if i found something better...