I have one xtragrid control on my devxpress form . I've created the columns of my grid at runtime when i load the form . I'm developing the Field chooser for my grid view which is situated on the same form. For that i used the repositoryItemCheckedComboBoxEditcontrol & in that control i added the column names which will be present in the xtragrid.
Basically i created the columns to the xtragrid with the Visible property to false. When user checks particular column name by using repositoryItemCheckedComboBoxEdit then i set the Visible to true & again if user unchecked the column name then again i set the visible to false. & while creating column i set the width of the column.
Problem which i'm facing is that if user select the all fields from the repositoryItemCheckedComboBoxEdit then the grid control should show the horizontal scroll bar automatically when require.
And another problem is that with the columns is besides setting the width of the column, it is not showing the required width of that column . it shrinks that all column width .
code which i use for creating column to the xtragridview at run time is as follows -
public void AddGridColumn(string fieldName, string caption, int nRowWidth, RepositoryItem Item, object oCollection, string DisplayMember, string ValueMember, string format, FormatType type)
{
DevExpress.XtraGrid.Columns.GridColumn column = ColumnView.Columns.AddField(fieldName);
column.Caption = caption;
column.ColumnEdit = Item;
column.DisplayFormat.FormatType = type;
column.DisplayFormat.FormatString = format;
column.VisibleIndex = ColumnView.VisibleColumns.Count;
column.Width = nRowWidth;
}
code for the field chooser is as follows -
I used this function for filling the items of the repositoryItemCheckedComboBoxEdit control
private void FieldCollection()
{
allFields = new ArrayList();
columnNames = new Dictionary<string, string>();
allFields.Clear();
repositoryItemCheckedComboBoxEdit1.Items.Clear();
for (int i = 0; i < gvBase.Columns.Count; i++)
{
allFields.Add(gvBase.Columns[i].Caption );
if (gvBase.Columns[i].FieldName != "ContactID")
{
if (gvBase.Columns[i].Visible == true)
{
if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Checked);
if (!columnNames.ContainsKey(gvBase.Columns[i].Caption))
columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
}
else
{
if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Unchecked);
if (!columnNames.ContainsKey(gvBase.Columns[i].FieldName))
columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
}
}
}
cmbFieldChooser.EditValue = "";
}
this is used for the repositoryItemCheckedComboBoxEdit control event -
private void cmbFieldChooser_EditValueChanged(object sender, EventArgs e)
{
ArrayList temp = new ArrayList();
temp.AddRange(allFields);
string[] strFields = cmbFieldChooser.EditValue.ToString().Split(',');
for (int i = 0; i < strFields.Length; i++)
{
if (temp.Contains(strFields[i].Trim()))
temp.Remove(strFields[i].Trim());
if (strFields[i] != "")
{
if (columnNames.ContainsKey(strFields[i].Trim()))
{
if (gvBase.Columns[columnNames[strFields[i].Trim()]].Visible == false)
{
gvBase.Columns[columnNames[strFields[i].Trim()]].Visible = true;
gvBase.Columns[columnNames[strFields[i].Trim()]].BestFit();
}
}
}
}
if (temp.Count < 20)
{
for (int j = 0; j < temp.Count; j++)
{
if (columnNames.ContainsKey(temp[j].ToString().Trim()))
{
gvBase.Columns[columnNames[temp[j].ToString().Trim()]].Visible = false;
}
}
}
cmbFieldChooser.EditValue = repositoryItemCheckedComboBoxEdit1.GetCheckedItems();
if ((cmbFieldChooser.EditValue.ToString()).Split(',').Length > 5)
{
gvBase.OptionsView.ColumnAutoWidth = false;
gvBase.BestFitColumns();
gvBase.HorzScrollVisibility = ScrollVisibility.Always;
}
else
{
gvBase.OptionsView.ColumnAutoWidth = true;
gvBase.HorzScrollVisibility = ScrollVisibility.Never;
}
}
How to resolve this problem?
thanks.
How many columns do you have in your Grid?
I see you have code there to turn off the ColumnAutoWidth once you go past 5 columns (ie 6 columns or more). Have you debugged this condition to ensure the ColumnAutoWidth is indeed being turned off?
As per BestFitColumns Help Doc the BestFitColumns will only calculate for the first n rows as per the BestFitMaxRowCount property unless it it set to -1, could this be a cause?
The other thing that seems a little odd if that you are setting the EditValue of cmdFieldChooser within the cmdFieldChooser_EditValueChanged event... why so?
Related
I am trying to create a datagrid tha shows values that have different timespans and due to what value a column in the row has the whole row changes color. I first tried to use DataGrid_LoadingRow And the values changed so I used a different approach but the same problem exist.
C#
MainDataGrid.ItemsSource = FileDifferences;
foreach (DataGridRow row in CreateRowsFromDataGrid(MainDataGrid))
{
var File = row.DataContext as FileDifference;
if (File.Time_Difference.TotalSeconds < 5.5)
{
// Nothing happens here
}
else if (File.Time_Difference.TotalSeconds < 10.5)
{
row.Background = new SolidColorBrush(Colors.Yellow);
}
else if (File.Time_Difference.TotalSeconds < 20.5)
{
row.Background = new SolidColorBrush(Colors.Orange);
}
else if (File.Time_Difference.TotalSeconds >= 20.5)
{
row.Background = new SolidColorBrush(Colors.Red);
}
}
private List<DataGridRow> CreateRowsFromDataGrid(DataGrid dg)
{
List<DataGridRow> randomRowTesting = new List<DataGridRow>();
for (int i = 0; i < dg.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);
if (row == null)
{
dg.UpdateLayout();
dg.ScrollIntoView(dg.Items[i]);
row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);
}
dg.ScrollIntoView(dg.Items[0]);
randomRowTesting.Add(row);
}
return randomRowTesting;
}
Any help is appreciated!
EDIT:
So what my problem is is that the color is moving to a different row that shouldn't be colored when I'm scrolling and it keeps on moving to random rows when I scroll up and down. What I want is to stop that from happening.
I have 2 gridControl and I wanna change background of cells (rows) that different between 2 gridControl with primary key is multiple field set by user.
Any solution for this problem?
See this example image
In this two query, key field is col1, col2, col3 and col4. Different in col6 and I want to highlight cell that have different value.
This is my current code for RowCellStyle event
private void gvQuery1_RowCellStyle(object sender, RowCellStyleEventArgs e)
{
if (gcQuery2.DataSource == null || lsKey == null || lsKey.Count <= 0)
return;
List<object> id = new List<object>();
foreach (KeyObject key in lsKey)
{
id.Add((sender as GridView).GetRowCellValue(e.RowHandle, key.key1[1].ToString()));
}
for (int i = 0; i < gvQuery2.RowCount; i++)
{
int rowHandle = gvQuery2.GetVisibleRowHandle(i);
bool flgEqual = true;
for (int j = 0; j < lsKey.Count; j++)
{
object v = gvQuery2.GetRowCellValue(rowHandle, gvQuery2.VisibleColumns[int.Parse(lsKey[j].key2[0].ToString())]);
if (id[j] == null && v == null)
continue;
if (!id[j].GetType().Equals(v.GetType()) || !id[j].ToString().Equals(v.ToString()))
{
flgEqual = false;
break;
}
}
if (flgEqual)
{
for (int k = 0; k < (sender as GridView).Columns.Count; k++)
{
if (!(sender as GridView).GetRowCellValue(e.RowHandle, (sender as GridView).Columns[k].FieldName).ToString()
.Equals(gvQuery2.GetRowCellValue(rowHandle, (sender as GridView).Columns[k].FieldName).ToString()))
{
if (e.Column.FieldName.Equals((sender as GridView).Columns[k].FieldName))
e.Appearance.BackColor = Color.Orange;
}
}
break;
}
}
}
Refer this: Customizing Appearances of Individual Rows and Cells
You can implement your functionality using the
GridView.RowCellStyle event. This event is fired for each cell in
a Grid View and thus it has Column and RowHandle parameters
that identify the cell being painted.
I assume that you have fixed number of records in both grid and also the order of the records are same. Then you can try to user same row handle to access the value from the both grid's MainView at RowCellStyle event as below:
using DevExpress.XtraGrid.Views.Grid;
// ...
private void gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e) {
GridView View = sender as GridView;
GridView leftGridView = leftGrid.MainView as GridView; //It is up to you that which viewtype you have used.
if(e.Column.FieldName == "Col5") {
string srcVal= View.GetRowCellDisplayText(e.RowHandle, View.Columns["Col5"]); // You can use GetRowCellValue() method also to get the value from the cell.
string leftGridVal= leftGridView .GetRowCellDisplayText(e.RowHandle, leftGridView .Columns["Col5"]);
if(srcVal != leftGridVal) {
e.Appearance.BackColor = Color.DeepSkyBlue;
e.Appearance.BackColor2 = Color.LightCyan;
}
}
}
Above code snippet is just like a sudo code to direct you to implement the functionality.. Handle this event on that Grid on which you want to color.. Remember to take care about the RowHandle, you have take care about the row index.
Hope this help..
Use the GridView.RowCellStyle event, which enables appearance settings of individual cells to be changed
Please refer this site for your reference
https://www.devexpress.com/Support/Center/Question/Details/Q520842
void gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e)
{
GridView currentView = sender as GridView;
if (e.Column.FieldName == "Customer")
{
bool value = Convert.ToBoolean(currentView.GetRowCellValue(e.RowHandle, "Flag_Customer"));
if (value)
e.Appearance.BackColor = Color.Red;
}
if (e.Column.FieldName == "Vendor")
{
bool value = Convert.ToBoolean(currentView.GetRowCellValue(e.RowHandle, "Flat_Vendor"));
if (value)
e.Appearance.BackColor = Color.Red;
}
}
I've added a Image Column to my datagrid in my c# winform, and I'm trying display an image depending on if the database value is "1". But all I get is the same image in all the rows that is set by the else statement,
Here is the column info
dgvPatList.Columns[8].Name = "NPO";
dgvPatList.Columns[8].HeaderText = "NPO";
dgvPatList.Columns[8].DataPropertyName = "NPO"
dgvPatList.Columns[8].Width = 50;
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.HeaderText = "NPO";
imageColumn.Name = "NPOIMG";
dgvPatList.Columns.Add(imageColumn);
and here's the code to add the image
private void dgvPatList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
int number_of_rows = dgvPatList.RowCount;
for (int i = 0; i < number_of_rows; i++)
{
if (dgvPatList.Rows[i].Cells[0].Value.ToString() == "1")
{
Icon image = Properties.Resources.Tick_Green;
this.dgvPatList.Rows[i].Cells["NPOIMG"].Value = image;
}
else
{
Icon image = Properties.Resources.no_results;
this.dgvPatList.Rows[i].Cells["NPOIMG"].Value = image;
//((DataGridViewImageCell)this.dgvPatList.Rows[i].Cells["NPOIMG"]).Value = Properties.Resources.no_results;
}
}
}
This should work, assuming your condition of 1 is actually being hit.. It will also deal with null values (if any).
foreach (DataGridViewRow dgRow in dgvPatList.Rows)
{
if (dgRow.Cells[0].Value == null) continue; //Change if you wish no_results to be shown
dgRow.Cells["NPOIMG"].Value = dgRow.Cells[0].Value.ToString() == "1"
? Properties.Resources.Tick_Green
: Properties.Resources.no_results;
}
Example shown below..
Maybe your criteria is always true or always false.
But I Checked this way using a correct criteria and it works:
foreach (DataGridViewRow row in myDataGridView.Rows)
{
if (row.IsNewRow)
continue;
if (row.Cells[0].Value.ToString() == "1")
row.Cells["ImageColumn"].Value = Properties.Resources.Image1;
else
row.Cells["ImageColumn"].Value = Properties.Resources.Image2;
}
I have a drop down list "ddlMitchelLandscape2" ,when add button triggers ,i add the selected item value in to gridview.
I am stuck here ,how to check the gridview, before add the value to grid view. The selected item is already exist in grid view or not when the add button is triggered .
Some one help me how to check the value is exist in gridview before add it to gird view please ?
protected void btnAddMitchellLandscape_Click(object sender, EventArgs e)
{
//validate to make sure Mitchell Landscape is entered
if (!ValidateMitchellPage())
return;
Assessment objAssessment = (Assessment)Session[Session_CurrentAssessment];
if (ddlMitchelLandscape2.GetSelectedItemValue > 0)
{
if (lblMitchellID.Text == string.Empty)
{
//add
AssessmentEntity objAssessmentEntity = new AssessmentEntity();
Assessment.tblMitchellLandscapeIDRow row =
objAssessment.tblMitchellLandscapeID.NewtblMitchellLandscapeIDRow();
row.MitchellLandscapeID = ddlMitchelLandscape2.GetSelectedItemValue;
row.MitchellLandscapeName = ddlMitchelLandscape2.GetSelectedItemText;
}
else
{
//Add button not visible when its not a new row
ctrlHeader.ShowError("Error: Unknown error");
return;
}
//refresh data bound table
PopulateMitchellDetailsToForm(ref objAssessment);
//clear after save
btnClearMitchellLandscape_Click(null, null);
}
}
ValidateMitchellPage()
private bool ValidateMitchellPage()
{
litMitchellError.Text = string.Empty;
if (ddlMitchelLandscape2.GetSelectedItemValue <= 0)
litMitchellError.Text = "Please select Mitchell Landscape";
if (litMitchellError.Text.Trim() == string.Empty)
{
litMitchellError.Visible = false;
return true;
}
litMitchellError.Visible = true;
return false;
}
DataBind to grid view
private void PopulateMitchellDetailsToForm(ref Assessment objAssessment)
{
Assessment.tblMitchellLandscapeIDRow[] MlData
= (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select("SaveType <> " + Convert.ToString((int)EnumCollection.SaveType.RemoveOnly));
this.gvMitchellLandscape.DataSource = MlData;
this.gvMitchellLandscape.DataBind();
}
You have to check the selected value from the dropdown or combobox in gridview by checking each row.
You can use following code to get row of gridview.
bool isValueExist=False;
for (int i = 0; i < gridview.Rows.Count; i++)
{
String val = gridview.Rows[i].Cells[0].Value.ToString();
if(val == your_drop_down_value)
{
isValueExist=True;
break;
}
}
You have to change the cell number according to your gridview design.
I want to group rows which is having same Name in DataGridView on Windows Forms below is the image what I want to implement.
Is it possible to implement below without using any third party tool ?
in the DataGridView place the following code in the
dgvProduct_CellFormatting Event
If e.RowIndex > 0 And e.ColumnIndex = 0 Then
If dgvProduct.Item(0, e.RowIndex - 1).Value = e.Value Then
e.Value = ""
ElseIf e.RowIndex < dgvProduct.Rows.Count - 1 Then
dgvProduct.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.White
End If
End If
All done!
Enjoy
You could try using the functionality of MSFlexGrid's MergeCells property of vertical cell merging instead of row grouping as explained in this article DataGridView Grouping in C#/VB.NET: Two Recipes. In this example, rows which belong to a group are joined visually using cells merged vertically - instead of using classical horizontal group rows.
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs args)
{
base.OnCellPainting(args);
args.AdvancedBorderStyle.Bottom =
DataGridViewAdvancedCellBorderStyle.None;
// Ignore column and row headers and first row
if (args.RowIndex < 1 || args.ColumnIndex < 0)
return;
if (IsRepeatedCellValue(args.RowIndex, args.ColumnIndex))
{
args.AdvancedBorderStyle.Top =
DataGridViewAdvancedCellBorderStyle.None;
}
else
{
args.AdvancedBorderStyle.Top = AdvancedCellBorderStyle.Top;
}
}
To supplement the (chosen) answer, here's the full code. The unmentioned idea is a class extending the DataGridView class.
public class GroupByGrid : DataGridView
{
protected override void OnCellFormatting(
DataGridViewCellFormattingEventArgs args)
{
// Call home to base
base.OnCellFormatting(args);
// First row always displays
if (args.RowIndex == 0)
return;
if (IsRepeatedCellValue(args.RowIndex, args.ColumnIndex))
{
args.Value = string.Empty;
args.FormattingApplied = true;
}
}
private bool IsRepeatedCellValue(int rowIndex, int colIndex)
{
DataGridViewCell currCell =
Rows[rowIndex].Cells[colIndex];
DataGridViewCell prevCell =
Rows[rowIndex - 1].Cells[colIndex];
if ((currCell.Value == prevCell.Value) ||
(currCell.Value != null && prevCell.Value != null &&
currCell.Value.ToString() == prevCell.Value.ToString()))
{
return true;
}
else
{
return false;
}
}
protected override void OnCellPainting(
DataGridViewCellPaintingEventArgs args)
{
base.OnCellPainting(args);
args.AdvancedBorderStyle.Bottom =
DataGridViewAdvancedCellBorderStyle.None;
// Ignore column and row headers and first row
if (args.RowIndex < 1 || args.ColumnIndex < 0)
return;
if (IsRepeatedCellValue(args.RowIndex, args.ColumnIndex))
{
args.AdvancedBorderStyle.Top =
DataGridViewAdvancedCellBorderStyle.None;
}
else
{
args.AdvancedBorderStyle.Top = AdvancedCellBorderStyle.Top;
}
}
}
source courtesy of social.msdn.microsoft