Number of Columns a DataRowView has? - wpf

I have a method SelectedRow() that grabs the content of a selected DataGrid row
private System.Data.DataRowView SelectedRow()
{
System.Data.DataRowView row = (System.Data.DataRowView)dgBrokerages.SelectedItems[0];
return row;
}
and would like to know how I can obtain an int containing the number of Columns that row contains.
private int NumColumns()
{
System.Data.DataRowView row = SelectedRow();
return row.Length; // <- Something like that
}
I'm basically looking for if there is a row.Length or row.Size?
Thanks,
iato

Try this:
private int NumColumns()
{
System.Data.DataRowView row = SelectedRow();
return row.Row.Table.Columns.Count;
}

Related

Ignore blank values in WPF chart control

I am working on WPF application which includes WPF chart. I am facing a situation.
I want to draw the chart only for values by ignoring blank values.
In application the data is contained by a datagrid and same data will be reflected in the graph, but datagrid having blank values(DBNull.Value).
So, I want to generate graph with only values by ignoring the blank values.
Here is my code for generating graph.
for (int col = 1; col < dtGeneric.Columns.Count; col++)
{
valueList = new List<KeyValuePair<string, double>>();
gLineSeries= new System.Windows.Controls.DataVisualization.Charting.LineSeries();
for (int row = 0; row < dtGeneric.Rows.Count - 1; row++)
{
if (string.IsNullOrEmpty(XaxisValue))
{
XaxisValue = "0";
}
YAxisValue = dtGeneric.Rows[row][col].ToString();
if (string.IsNullOrEmpty(YAxisValue))
{
YAxisValue = "0";
}
valueList.Add(new KeyValuePair<string, double>(XaxisValue, Convert.ToDouble(YAxisValue)));
}
gLineSeries.DependentValuePath = "Value";
gLineSeries.Style = gLineSeries.PolylineStyle;
gLineSeries.IndependentValuePath = "Key";
gLineSeries.ItemsSource = valueList;
gLineSeries.Title = dtGeneric.Columns[col].Caption.Replace('_', '.').ToString();
gLineSeries.AnimationSequence = AnimationSequence.FirstToLast;
chartControl.Series.Add(gLineSeries);
}
}
As you can see in the code, I have used keyvaluepair to draw the graph. So I am unable to add null value in the Value of keyvaluepair. I have tried with double.NaN but that is not working.
I have iterated all the columns because all the column will have its separate graph.
I have tried one logic to create the graph which is:
for (int col = 1; col < dtGeneric.Columns.Count; col++)
{
valueList = new List<KeyValuePair<string, double>>();
gPositionLineSeries = new System.Windows.Controls.DataVisualization.Charting.LineSeries();
for (int row = 0; row < dtGeneric.Rows.Count - 1; row++)
{
if (!string.IsNullOrEmpty(dtGeneric.Rows[row][0].ToString()) && !string.IsNullOrEmpty(dtGeneric.Rows[row][col].ToString())) //Null values will be ignored for graph generation...
{
XaxisValue = dtGeneric.Rows[row][0].ToString();
YAxisValue = dtGeneric.Rows[row][col].ToString();
valueList.Add(new KeyValuePair<string, double>(XaxisValue, Convert.ToDouble(YAxisValue)));
}
else
{
continue;
}
}
}
Above code is working fine but the X-axis values in the graph is not in order.
Please tell me some solution.
use below code in if block
string.IsNullOrEmpty(row.Cells[clm.Index].Value.ToString())

SUM of "Amount" column in DATAGRID's DataGridTemplateColumn RUNTIME

We have WPF application, In which we use DataGrid on one form.
At runtime, when we Enter value in DataTemplate column, I need to Show SUM of that specific column in DATAGRID Footer.
So when each time I change value in any Cell of That AMOUNT column, The correct SUM of that column need to be display.
Which event I should try.
I have tried this code , But it need to press tab each time, it does not display Correct SUM.
private void dgInfo_RowEditEnding(object sender, Microsoft.Windows.Controls.DataGridRowEditEndingEventArgs e)
{
Microsoft.Windows.Controls.DataGridRow row = this.dgInfo.ItemContainerGenerator.ContainerFromIndex(e.Row.GetIndex()) as Microsoft.Windows.Controls.DataGridRow;
ContentPresenter CP = dgInfo.Columns[3].GetCellContent(row) as ContentPresenter;
TextBlock t = FindVisualChild<TextBlock>(CP);
if (t != null && t.Text.Length > 0)
{
decimal d = Convert.ToDecimal(t.Text);
sum = sum + d;
txtTotal.Text = sum.ToString();
}
}
void dgInfo_CellEditEnding(object sender, Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs e)
{
decimal tot = 0;
GetFaltyExpenseGridResult newRecord;
for (int i = 0; i < (dgInfo.Items.Count - 1); i++)
{
newRecord = (GetFaltyExpenseGridResult)((ContentPresenter)dgInfo.Columns[0].GetCellContent(dgInfo.Items[i])).Content;
if (newRecord != null)
{
decimal d = Convert.ToDecimal(newRecord.Amount);
tot = tot + d;
txtTotal.Text = tot.ToString();
}
}
}

Get all cells in datagrid

Is there a way to get an iteratable collection of all the cells in a DataGrid regardless of whether they are selected or not
If you mean DataGridCells you could use Vincent Sibals helper functions to iterate over all rows DataGrid.Items and columns DataGrid.Columns.
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
// now try to bring into view and retreive the cell
DataGrid_Standard.ScrollIntoView(rowContainer, DataGrid_Standard.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// may be virtualized, bring into view and try again
DataGrid_Standard.ScrollIntoView(DataGrid_Standard.Items[index]);
row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
Edit
If grid is your DataGrid you get a list of all DataGridCells like this:
List<DataGridCell> allCellList = new List<DataGridCell>();
for (int i = 0; i < grid.Items.Count; i++)
{
for (int j = 0; j < grid.Columns.Count; j++)
{
allCellList.Add(grid.GetCell(i, j));
}
}
For the sake of convenience (not necessarily performance), you can populate your data (including all cells from all column and rows) from your DataGrid to a single DataTable, which provides functions to help manipulate your data such as iteration, filtering, sorting etc.
// Populate a DataGrid to a DataTable
DataTable dt;
DataView dv = (DataView) myDataGrid.DataSource;
dt = dv.Table.DataSet.Tables[0];
You can subsequently convert any of a specific column to a collection or list using generics in as short as one line of code. See how-do-you-convert-a-datatable-into-a-generic-list:
List<DataRow> myList = dt.Rows.Cast<DataRow>().ToList();
It saves you from writing loops.
To fix the error thrown by the line...
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>
(rowContainer);
Add this routine:
private T GetVisualChild<T>(DataGridRow rowContainer)
{
throw new NotImplementedException();
}

Windows 8 GridView multi selected items

I am developing an application for Windows 8, I would like to select multiple items in a GridView (by c# code), I tried this:
1st
for (int i = 0; i <= 2; i++)
{
this.ItemGridView.SelectedIndex = i;
}
//in this way is only selects the third element
2nd
this.ItemGridView.SelectedItem = listPeople;
//in this way does not select anything
3rd
foreach (Persona persona in listaPersone)
{
this.ItemGridView.SelectedItem = person;
}
//in this way is selected only the last
You could try this
Assume the 'listPeople' is collection what you want to select.
foreach(var p in listPeople)
{
this.ItemGridView.SelectedItem.Add(p);
}
I didn't try for Win8 but something like this should work:
this.ItemGridView.MultiSelect = true;
foreach (GridViewRow row in this.ItemGridView.Rows)
{
row.Selected = selection.Contains(row.Cells[0].Value);
}

jCombobox giving incremental value error on jTable

I am having problems with my code below, the code below shows a jComboBox being populated, when i select an item from this list it is added to the jTable below it.
There is alos code to check for duplicate entries ont he table. If a duplicate entry is found it should increase the qty column by one and not create a seperate entry.
This is where the problem comes in, when I press the back button on this screen and go to a different screen and then come back via same route as the first time, I get an incrementally different qty added to the table row/cell.
I have also included the code that populates the Round Details depending on Round Drop selected from table, for reference, but Im fairly certain the problem lies in the below code. The navigation is as follows...
To get to the below screen... Round Drop panel table of round drops) >> click on table row and taken to associated round details panel >> pressing the Till button takes user to screen with code below...
Test results:
First pass through below code using navigation above gives results as expected
Second pass gives an initial value of 2 (instead of one), and duplicate row increases qty by 2 instead of one
Third pass gives an initial value of 3 (instead of one), and duplicate row increases qty by 3 instead of one
Fourth pass gives an initial value of 4 (instead of one), and duplicate row increases qty by 4 instead of one
...and so on.
Any help, guidance on solution or a better design would be hugely appreciated.
Thanks
/*************Code sample ********************************/
public void tillOperations(String sourceCall) {
final DefaultTableModel model = (DefaultTableModel)main.tillPanel.tblTillSale.getModel();
if (main.tillPanel.cmbTillProdSelect.getItemCount() < 1) {
for (int d = 0; d < roundStockObj.length ; d++) {
main.tillPanel.cmbTillProdSelect.addItem(roundStockObj[d].getDescription());
}}
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount() - 1);
main.tillPanel.cmbTillProdSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent f)
{
int qty = 1;
for (int index = 0; index < 4; index++) {
addSelectedItem[index] = "";
}
int row;
selectedItem = null;
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount() - 1);
selectedItem = main.tillPanel.cmbTillProdSelect.getSelectedItem();
for (int d = 0; d < roundStockObj.length; d++) {
if (selectedItem.equals(roundStockObj[d].getDescription())) {
addSelectedItem[0] = roundStockObj[d].getDescription();
addSelectedItem[1] = Integer.toString(qty);
addSelectedItem[2] = Double.toString(roundStockObj[d].getPrice()).trim();
addSelectedItem[3] = Double.toString(roundStockObj[d].getPrice()).trim();
//break;
}
}
if(model.getRowCount() == 0) { //check if model is empty
model.addRow(new String[]{addSelectedItem[0], addSelectedItem[1], addSelectedItem[2], addSelectedItem[3]});
}
else { //check if there is a duplicate row
int duplicateRow = -1;
for (row = 0 ; row < model.getRowCount(); row++) {
if(addSelectedItem[0].equals(main.tillPanel.tblTillSale.getModel().getValueAt(row,0))) {
duplicateRow = row;
break;
}
}
if(duplicateRow == -1) { //if there is no duplicate row, append
model.addRow(new String[]{addSelectedItem[0], addSelectedItem[1], addSelectedItem[2], addSelectedItem[3]});
}
else { //if there is a duplicate row, update
main.tillPanel.jLabel1.setText(addSelectedItem[1]);
DecimalFormat fmtObj = new DecimalFormat("####0.00");
int currentValue = Integer.parseInt(main.tillPanel.tblTillSale.getValueAt(row, 1).toString().trim());
int newValue = currentValue + 1;
Integer newValueInt = new Integer(newValue);
model.setValueAt(newValueInt, row, 1);
double unitPrice = Double.parseDouble(main.tillPanel.tblTillSale.getValueAt(row, 2).toString().trim());
double newPrice = newValue * unitPrice;
Double newPriceDbl = new Double(newPrice);
main.tillPanel.tblTillSale.setValueAt(fmtObj.format(newPriceDbl), row, 3);
}
}
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount() - 1);
for (int index = 0; index < 4; index++) {
addSelectedItem[index] = "";
}
}
});
//This code loads the specific Round Details, based on the selection form the round drops table
public void displayRoundDropDetails() {
DefaultTableModel model = (DefaultTableModel)main.selectRoundDropPanel.tblSelectRoundDrop.getModel();
if (!loaded) {
for (int d = 0; d < roundDropsData.length; d++) {
if (roundDropsData[d][0].equals(defaultRoundID)) {
model.addRow(new Object[]{roundDropsData[d][3], roundDropsData[d][2],
roundDropsData[d][4], roundDropsData[d][5]});
}
}
loaded = true;
}
main.selectRoundDropPanel.tblSelectRoundDrop.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int row = 0;
row = main.selectRoundDropPanel.tblSelectRoundDrop.getSelectedRow();
for (int index = 0; index < roundDropsData.length; index++) {
if (roundDropsData[index][3].equals(
main.selectRoundDropPanel.tblSelectRoundDrop.getModel().getValueAt(row, 0))) {
main.roundDetailsPanel.txtRoundDetailsAddress.setText(roundDropsData[index][6] + "\n"
+ roundDropsData[index][7] + ", " + roundDropsData[index][8] + "\n" +
roundDropsData[index][9]);
main.roundDetailsPanel.lblRoundDetailsName.setText(roundDropsData[index][2]);
main.roundDetailsPanel.txtRoundDetailsInstuct.setText(roundDropsData[index][10]);
main.roundDetailsPanel.txtDropDetailsIn.setText(roundDropsData[index][4]);
main.roundDetailsPanel.txtDropDetailsOut.setText(roundDropsData[index][5]);
main.roundDetailsPanel.txtRoundDetailsInstruct.setText(roundDropsData[index][12]);
break;
}
}
Globals.CURRENT_COMPONENT = "selectRoundDropPanel";
showRoundDetailsPanel();
}
});
}
Try changing the listener for JComboBox. try using stateChangeListener.

Resources