DataGrid gets the value of a row and column - datagrid

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();
}

Related

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>();

How to change the color of a gridview cell based on criteria?

This is my gridview output. The Column and row will be binded dynamically.
Anand R 4:4:18 NULL 6:34:52 8:25:16 NULL
Arunkumar S 8:37:31 NULL 9:1:42 8:48:27 NULL
Bharathi R 6:12:24 NULL 8:45:40 11:39:12 12:27:26
Gnanaguru V 6:32:20 NULL 5:35:56 3:50:20 NULL
Ilayaraja K 7:37:30 NULL 10:1:15 8:58:43 NULL
Imran Khan S 7:46:48 NULL 12:15:4 NULL NULL
I need output as if the cell value is greater than 8:30 hours means i need some color and below than 8:30 the cell should be in some color and for the null value the original remain same. So i need to loop through gridview rows and columns dynamically to check the condition. I am using following code in gridview rowdatabound but am not getting exact output..
foreach (GridViewRow row in gvshowreport.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (i != 0)
{
string value = row.Cells[i].Text;
if (value != " ")
{
string[] values = Regex.Split(value, ":");
int k = Convert.ToInt32(values[0]);
int m = Convert.ToInt32(values[1]);
int min = k * 60;
int add = min + m;
if (add <= 510)
{
e.Row.Cells[i].BackColor = System.Drawing.Color.LightGreen;
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Red;
}
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.PaleGoldenrod;
}
}
}
}
First time my loop is running perfectly it taking the gridview first row and cell values. While next time loop running it again taking the same first row cell values. I think i have did mistake looping through the rows and columns...
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach(TableCell cell in e.Row.Cells)
val = cell.Text;
}
I have use this code to achieve my result.. Thanks for everyone posting
as your code, you should replace "e.Row.Cells[i]" with variable "row"
We would change the color of cell in Row_dataBound Event of Gridview
When a single record bind with a gridView Row_dataBound event fires
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Your Cell Control Find, than change the color according to condition
}
}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound%28v=vs.110%29.aspx
Please mark it answer if it helps you

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
};

Specific row withing a DataTable

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.

Resources