I want to clear all controls specially textbox nad combobox.
and I am using the following control to clear all fields.
private void ResetFields()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
if (tb != null)
{
tb.Text = string.Empty;
}
}
else if (ctrl is ComboBox)
{
ComboBox dd = (ComboBox)ctrl;
if (dd != null)
{
dd.Text = string.Empty;
dd.SelectedIndex = -1;
}
}
}
}
The above code is not working properly in group box. In group box I have combo box and text box as well. Combo box shows the selected index = 1 of the group box. I also want to clear these controls as well.
Any suggestions ????
For TextBox and ComboBox
public static void ClearSpace(Control control)
{
foreach (Control c in control.Controls)
{
var textBox = c as TextBox;
var comboBox = c as ComboBox;
if (textBox != null)
(textBox).Clear();
if (comboBox != null)
comboBox.SelectedIndex = -1;
if (c.HasChildren)
ClearSpace(c);
}
}
Usage:
ClearSpace(this); //Control
Related
I have a form with TextBoxes, ComboBoxes, CheckBoxes, DataGridView inside a panel. On a Button Click event I have the following procedure to clear the controls:
public void ClearControlValues(Control Container)
{
try
{
foreach (Control ctrl in Container.Controls)
{
if (ctrl.GetType() == typeof(TextBox))
{
((TextBox)ctrl).Text = "";
}
if (ctrl.GetType() == typeof(ComboBox))
{
((ComboBox)ctrl).SelectedIndex = -1;
}
if (ctrl.GetType() == typeof(CheckBox))
{
((CheckBox)ctrl).Checked = false;
}
if (ctrl.GetType() == typeof(DateTimePicker))
{
((DateTimePicker)ctrl).Text = "";
}
if (ctrl.GetType() == typeof(DataGrid))
{
((DateTimePicker)ctrl).Text = "";
}
if (ctrl.Controls.Count > 0)
{
LockControlValues(ctrl);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Button Click calling:
ClearControlValues(this);
But:
Controls inside my panel "MainPanel" is not clearing. What do I am missing?
This code solve the problem:
public void ClearControlValues(Control Container)
{
foreach (Control c in Container.Controls)
{
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Checked = false;
}
if (c is TextBox)
{
TextBox tb = (TextBox)c;
tb.Text = "";
}
if (c is ComboBox)
{
ComboBox cb = (ComboBox)c;
cb.SelectedIndex = -1;
}
if (c is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)c;
dtp.Text = DateTime.Today.ToString();
}
if (c is DataGridView)
{
DataGridView dgv = (DataGridView)c;
dgv.Rows.Clear();
dgv.Refresh();
}
}
}
Calling:
ClearControlValues(MainPanel);
Thank you,
WPF DataGrid while adding new row focus is always setting to last position of cell.
How would I can set to the first cell's focus while adding new row?
1.I have simple 6 columns so when I press enter on last column it should add new row (working fine)
2.Focus should be the added row's first cell it won't happen it is always in the last cell
I am attaching my WPF Sample demo as well please correct me where I am wrong?
Demo Link: WPFDemo
Thank you,
Jitendra Jadav.
You could handle previewkeydown on the datagrid:
private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
{
var el = e.OriginalSource as UIElement;
if (e.Key == Key.Enter && el != null)
{
e.Handled = true;
el.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
The markup is probably obvious but:
<DataGrid Name="dg"
...
PreviewKeyDown="dg_PreviewKeyDown"
There may well be some unexpected side effects, I just tested you hit enter in the last cell and you end up in the first cell of the next row OK.
You could handle the CellEditEnding event and get a reference to the DataGridCell as explained in the following blog post.
How to programmatically select and focus a row or cell in a DataGrid in WPF: https://blog.magnusmontin.net/2013/11/08/how-to-programmatically-select-and-focus-a-row-or-cell-in-a-datagrid-in-wpf/
This seems to work for me:
private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromItem(CollectionView.NewItemPlaceholder) as DataGridRow;
if (row != null)
{
dataGrid.SelectedItem = row.DataContext;
DataGridCell cell = GetCell(dataGrid, row, 0);
if (cell != null)
dataGrid.CurrentCell = new DataGridCellInfo(cell);
}
}
private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
{
if (rowContainer != null)
{
DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
if (presenter != null)
return presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
}
return null;
}
private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
I used this code, select first cell and fix tab focuse out of datagride:
private void table_PreviewKeyDown(object sender, KeyEventArgs e)
{
var el = e.OriginalSource as UIElement;
if (e.Key == Key.Enter && el != null)
{
table.CurrentCell = new DataGridCellInfo(table.Items[table.Items.Count-1], table.Columns[0]);
table.SelectedCells.Clear();
table.SelectedCells.Add(table.CurrentCell);
}else if (e.Key == Key.Tab && el != null && table.SelectedCells[0].Column.DisplayIndex > table.Items.Count)
{
table.Focus();
}
}
public void MouseSingleClickEditable(object sender, MouseButtonEventArgs e)
{
if ((!datagrid.HasItems) || datagrid.SelectedIndex < 0) return;
DataGridColumn clmn = datagrid.CurrentColumn;
if (clmn != null)
{
String columnType = clmn.GetType().Name;
switch (columnType)
{
case "DataGridTemplateColumn":
case "DataGridCheckBoxColumn":
row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(datagrid.Items[datagrid.SelectedIndex]);
if (!row.IsEditing)
{
datagrid.IsReadOnly = false;
datagrid.BeginEdit();
}
break;
default:
break;
}
}
}
I have 2 DatePickers, Checkbox and a combobox in my WPF Datagrid but while geeting the column type I am getting it only as DataGridTemplateColumn instead of type DataGridDatePickerColumn or DataGridComboboxColumn. How to extract the exact type of Control from the DataGridTemplateColumn.
public void MouseSingleClickEditable(object sender, MouseButtonEventArgs e) {
var datagrid = new DataGrid();
if ((!datagrid.HasItems) || datagrid.SelectedIndex < 0) return;
DataGridColumn clmn = datagrid.CurrentColumn;
if (clmn != null) {
if (clmn is DataGridCheckBoxColumn) {
//do something
} else if (clmn is DataGridTemplateColumn) {
var templateColumn = (DataGridTemplateColumn)clmn;
var rootControlOfCellTemplate = templateColumn.CellTemplate.LoadContent();
var rootControlOfCellEditingTemplate = templateColumn.CellEditingTemplate.LoadContent();
// you can now check for types of the template. CellEditingTemplate is for template in edit mode, and CellTemplate for "non-edit" mode
// for example
if (rootControlOfCellTemplate is Button) {
//do something
}
if (rootControlOfCellEditingTemplate is DatePicker) {
//do something
}
}
}
}
Note how I check for types. Normally you should do it like this, not by hard-coded strings.
I have a problem regarding the comportment my ComboBox.
First I use a combobox to display all elements in a IEnumarale.
Then, with a button wich open a popup, the user can add an alement to that list.
The problem is that when the user validate his choice and close the popup, the element is not automatly added to the ComboBox without doing a refresh of the page.
The combobox is coded as follows :
<telerik:RadComboBox x:Name="MyElements"
SelectionChanged="MyElements_OnSelectionChanged"
ItemTemplate="{StaticResource ComboBoxElementsTemplate}"
ItemsSource="{Binding ListElements}"/>
The constructor of the list is :
public IEnumerable<Element> ListElements
{
get { return _listElements; }
set
{
_listElements= value;
RaisePropertyChange("ListElements");
}
}
And the code behind of the button to validate the user choice in the popup :
private ObservableCollection<HistoriqueElement> elementList = null;
private void SelectClick(object sender, RoutedEventArgs e)
{
var element= _GridList.SelectedItem as HistoriquePasserelle;
if (_GridList.SelectedItem != null)
{
var installation = this.DataContext as Installation;
if (installation != null && element!= null)
{
element.DateFin = DateTime.Now;
HistoriqueElement newElement= new HistoriqueElement()
{
Installation = installation,
ContactAction = GlobalActeurs.Current.CurrentContact,
Date = DateTime.Now,
Element = element.Element,
StatutElement = element.StatutElement ,
Owner= element.Owner,
};
elementList.Remove(element);
}
MainPage.ClosePopup();
}
}
When the user choose a new element in the list display in the popup and validate his choice, he returns to the main page, but his choice is not automatically added to the combobox.
I can post you any parts of the code.
Thank you in advance.
The method OnDataContextChanged :
public override void OnDataContextChanged(DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is Installation)
{
if (MainPage.CurrentInstallation.LastElements != null)
{
ListElements = MainPage.CurrentInstallation.LastElements;
MyElements.SelectedIndex = 0;
}
else
{
LoadOperation<Element> operation =
_context.Load(_context.GetCurrentElementsByInstallationId(MainPage.CurrentInstallation.Id));
this._busy.IsBusy = true;
operation.Completed += delegate
{
this._busy.IsBusy = false;
if (operation.ManageError())
{
ListElements = operation.Entities;
}
};
}
this.DataContext = this;
}
else
{
RaisePageTitleChanged();
if (MainPage.CurrentInstallation == null)
return;
}
if (MyElements.SelectedItem == null && MyElements.Items.Any())
{
MyElements.SelectedIndex = 0;
}
}
If the collection the ItemsSource is bound to implement INotifyCollection changed, that is, it's an ObservableCollection<>, then the combobox will be notified of any changes to the collection and you will not need to rebind or refresh, it will all be automatic.
Once you add the item to the list, bind the itemsource to the combobox, then you dont have to refersh.
MyElements.ItemsSource = ListElements
I use this code to add or remove column from datagrid. each column header I have mouse enter and leave event. For new column I also would like to add the same event handler after inserting to datagrid.
private void Columns_CollectionChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
{
if (e.Action == CollectionChangeAction.Add)
{
int columnPosition = (this.Columns.Count - 1);
DataGridTextColumn column = new DataGridTextColumn();
column.Header = (e.Element as DataColumn).ColumnName;
column.Binding = new Binding(string.Format("[{0}]", column.Header.ToString()));
this.Columns.Insert(columnPosition, column);
DataGridColumnHeader columnHeader = DataGridHelper.GetColumnHeader(this, columnPosition);
if (columnHeader != null)
{
columnHeader.MouseEnter += new MouseEventHandler(ColumnHeader_MouseEnter);
columnHeader.MouseLeave += new MouseEventHandler(ColumnHeader_MouseLeave);
}
SetAutomappingOnOff = false;
}
else if (e.Action == CollectionChangeAction.Remove)
{
DataColumn column = e.Element as DataColumn;
DataGridColumn toRemove = (from DataGridColumn dc in this.Columns
where dc.Header != null && dc.Header.ToString() == column.ColumnName
select dc).First();
this.Columns.Remove(toRemove);
SetAutomappingOnOff = false;
}
}
< Edit>
DataGridHelper
public static class DataGridHelper
{
public static DataGridColumnHeader GetColumnHeader(DataGrid dataGrid, int index)
{
DataGridColumnHeadersPresenter presenter = FindVisualChild<DataGridColumnHeadersPresenter>(dataGrid);
if (presenter != null) {
return (DataGridColumnHeader)presenter.ItemContainerGenerator.ContainerFromIndex(index);
}
return null;
}
}
< /Edit>
But columnHeader always returns null even though I can see that object is created and added to datagrid.
Pls help me.
Thanks
Dee
While the column has been added to the DataGrid, it hasn't yet been added to the VisualTree so your FindVisualChild method is returning null. I don't have a good solution for adding the click handler for the column, but you could add it to the DataGrid and check the sender to see where to apply the click handling logic.
I would suggest registering CollectionChanged event on DataGrid-s Loaded event. That way you can be sure that DataGridColumnHeader is added to the visual tree. It will look like this:
myDataGrid.Loaded += (s,e) => {
myCollection.CollectionChanged += (se, ev) => {
//do work here
};
};