c# winform to inspect an object during runtime - c#

I want to display the public Property/Values of an arbitrary object during runtime in a GUI.
Is there a winform which allows the user to view the content of any object like in debug mode? The object will hold many Dictionaries > and it would be nice to be able to expand and view the contents of those lists during runtime.
If not available, is there someway to achieve something similar?
Thanks

All you need to do is create a form with a PropertyGrid on it. Then set the selected object.
using xxx.CFM.UI.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace xxx.CFM.UI.Forms
{
/// <summary>
/// Form used to inspect objects at runtime
/// </summary>
public partial class frmInspector : BaseForm
{
#region Properties
/// <summary>
/// Gets or Sets the
/// </summary>
public object SelectedObject
{
get { return propertyGrid.SelectedObject; }
set { propertyGrid.SelectedObject = value; }
}
#endregion Properties
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public frmInspector(object objectToInspect)
{
try
{
InitializeComponent();
this.SelectedObject = objectToInspect;
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
#endregion Constructor
#region Events
/// <summary>
/// Closes the form
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void btnClose_Click(object sender, EventArgs e)
{
try
{
this.Close();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
#endregion Events
}
}
I use this on a context menu in a grid for example to expect the data record below it:
/// <summary>
/// Opens the object inspector
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void inspectorMenuItem_Click(object sender, EventArgs e)
{
try
{
//Get the payload
SectionDataTreeListMenuItemPayload payload = (sender as ToolStripMenuItem).Tag as SectionDataTreeListMenuItemPayload;
if (payload == null || payload.DataRow == null)
return;
using (frmInspector frmInspector = new frmInspector(payload.DataRow))
frmInspector.ShowDialog();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
another little trick you can do is to ensure the form is only available when built in debug mode by using the below code using a 'compiler directive'. (if you want it only used for debugging of course)
#if DEBUG
//Add object inspector menu item if built in debug mode
ToolStripMenuItem inspectorMenuItem = new ToolStripMenuItem();
inspectorMenuItem.Text = "Inspect Object";
inspectorMenuItem.Image = Properties.Resources.Inspect24x24;
inspectorMenuItem.Click += inspectorMenuItem_Click;
inspectorMenuItem.Tag = payload;
contextMenuStrip.Items.Add(inspectorMenuItem);
#endif

There's PropertyGrid:
var form = new Form();
form.Controls.Add
(
new PropertyGrid()
{
SelectedObject = new { A = "Hi", B = new [] { 32, 40 } }
}
);
form.Show();
It's quite far from how the debugger one works, but it can be quite easily modified to handle any special cases you might have.

Related

Creating a .csv file for my esurvey application. How do I start?

I'm having trouble with coding my Esurvey application(using Windows Store C# XAML) and I really need help. I need to create a .csv database which contains all results(radiobutton selections and text inputs) but I'm not sure where to even start.
Can someone help me with this? I'm using Visual Studio Community 2013.
using FYPPrototype1.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
namespace FYPPrototype1
{
/// <summary>
/// A basic page that provides characteristics common to most applications.
/// </summary>
///
public sealed partial class SurveyPage1 : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
/// <summary>
/// This can be changed to a strongly typed view model.
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
/// <summary>
/// NavigationHelper is used on each page to aid in navigation and
/// process lifetime management
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public SurveyPage1()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
if (e.PageState != null && e.PageState.ContainsKey("rbNumber1") && e.PageState.ContainsKey("rbNumber2") && e.PageState.ContainsKey("rbNumber3") && e.PageState.ContainsKey("rbNumber4"))
{
radioExcellent.IsChecked = (bool)e.PageState["rbNumber1"];
radioGood.IsChecked = (bool)e.PageState["rbNumber2"];
radioPoor.IsChecked = (bool)e.PageState["rbNumber3"];
radioAverage.IsChecked = (bool)e.PageState["rbNumber4"];
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState["rbNumber1"] = radioExcellent.IsChecked;
e.PageState["rbNumber2"] = radioGood.IsChecked;
e.PageState["rbNumber3"] = radioPoor.IsChecked;
e.PageState["rbNumber4"] = radioAverage.IsChecked;
}
#region NavigationHelper registration
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
private async void Button_S1_S2(object sender, RoutedEventArgs e)
{
if (radioExcellent.IsChecked != true && radioGood.IsChecked != true && radioAverage.IsChecked != true && radioPoor.IsChecked != true)
{
MessageDialog md = new MessageDialog("Please select an option before proceeding!");
await md.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(SurveyPage2));
}
}
}
}
Here is a screenshot of my application in case you need a reference.
This is the output that my teacher wants but I have no idea how to make it as shown :(
You can do it this way where "greetingOutputText" is the key
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Restore values stored in session state.
if (e.PageState != null && e.PageState.ContainsKey("greetingOutputText"))
{
greetingOutput.Text = e.PageState["greetingOutputText"].ToString();
}
}
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState["greetingOutputText"] = greetingOutput.Text;
}
This link will help you.

Creating a .csv file for my esurvey application. How do I start? (Duplicate)

I'm having trouble with coding my Esurvey application(using Windows Store C# XAML) and I really need help. I need to create a .csv database which contains all results(radiobutton selections and text inputs) but I'm not sure where to even start.
Can someone help me with this? I'm using Visual Studio Community 2013.
using FYPPrototype1.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
namespace FYPPrototype1
{
/// <summary>
/// A basic page that provides characteristics common to most applications.
/// </summary>
///
public sealed partial class SurveyPage1 : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
/// <summary>
/// This can be changed to a strongly typed view model.
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
/// <summary>
/// NavigationHelper is used on each page to aid in navigation and
/// process lifetime management
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public SurveyPage1()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
if (e.PageState != null && e.PageState.ContainsKey("rbNumber1") && e.PageState.ContainsKey("rbNumber2") && e.PageState.ContainsKey("rbNumber3") && e.PageState.ContainsKey("rbNumber4"))
{
radioExcellent.IsChecked = (bool)e.PageState["rbNumber1"];
radioGood.IsChecked = (bool)e.PageState["rbNumber2"];
radioPoor.IsChecked = (bool)e.PageState["rbNumber3"];
radioAverage.IsChecked = (bool)e.PageState["rbNumber4"];
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState["rbNumber1"] = radioExcellent.IsChecked;
e.PageState["rbNumber2"] = radioGood.IsChecked;
e.PageState["rbNumber3"] = radioPoor.IsChecked;
e.PageState["rbNumber4"] = radioAverage.IsChecked;
}
#region NavigationHelper registration
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
private async void Button_S1_S2(object sender, RoutedEventArgs e)
{
if (radioExcellent.IsChecked != true && radioGood.IsChecked != true && radioAverage.IsChecked != true && radioPoor.IsChecked != true)
{
MessageDialog md = new MessageDialog("Please select an option before proceeding!");
await md.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(SurveyPage2));
}
}
}
}
Here is a screenshot of my application in case you need a reference.
This is the output that my teacher wants but I have no idea how to make it as shown :(

Windows 8.1 App C# XAML help: Save radio button selection when navigating back to previous page

I'm trying to code an ESurvey application. I have a list of radio buttons in each page (A total of 7 pages), and I would like to make the radio buttons save its check state when the respondent clicks on the previous page.
using FYPPrototype1.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
namespace FYPPrototype1
{
/// <summary>
/// A basic page that provides characteristics common to most applications.
/// </summary>
public sealed partial class SurveyPage2 : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
/// <summary>
/// This can be changed to a strongly typed view model.
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
/// <summary>
/// NavigationHelper is used on each page to aid in navigation and
/// process lifetime management
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public SurveyPage2()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
}
#region NavigationHelper registration
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
private async void Button_S2_S3(object sender, RoutedEventArgs e)
{
if (RadioaAgree.IsChecked != true && RadioaNeutral.IsChecked != true && RadioaDisagree.IsChecked != true)
{
MessageDialog md = new MessageDialog("One or more options not selected. Please complete all options before proceeding!");
await md.ShowAsync();
}
else if (RadiobAgree.IsChecked != true && RadiobNeutral.IsChecked != true && RadiobDisagree.IsChecked != true)
{
MessageDialog md = new MessageDialog("One or more options not selected. Please complete all options before proceeding!");
await md.ShowAsync();
}
else if (RadiocAgree.IsChecked != true && RadiocNeutral.IsChecked != true && RadiocDisagree.IsChecked != true)
{
MessageDialog md = new MessageDialog("One or more options not selected. Please complete all options before proceeding!");
await md.ShowAsync();
}
else if (RadiodAgree.IsChecked != true && RadiodNeutral.IsChecked != true && RadiodDisagree.IsChecked != true)
{
MessageDialog md = new MessageDialog("One or more options not selected. Please complete all options before proceeding!");
await md.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(SurveyPage3));
}
}
}
}
Much appreciated to all the kind coders out there helping me out!
You can simply store a local variable, like a boolean, and when returning to that page check for the variable value and change radioButtons state accordingly ;)
// these is the namespace of your class
namespace FYPPrototype1
{
// these is the region of your class, where all functions and variables are stored
public sealed partial class SurveyPage2 : Page
{
// these are local variables
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
// this is your class constructor
public SurveyPage2()
{
InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
.
.
.
}
}
Now for achieve what you need, you have to do a more complex thing, as you can see you have a load and a save function, that is navigationHelper_LoadState and navigationHelper_SaveState, you can store and load there radioButtons's state ;)
For more understanding on how to manage these functions refer to these page, it explain it quite well ;): http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2014/05/23/windows-phone-8-1-frame-page-navigationhelper-suspensionmanager.aspx

How to change the language of the text on all control in the form

Is there a way to change the language of all the controls in the form in runtime?
For example, I have a button in the form and it has a text of "Hello". How can I change that into different language on runtime? dynamically every language that I can set. Is there a way to do it??
I've found an answer, but it seems that its not working it has something to do with cultureinfo. Any suggestions how to do it?
This is my code
public partial class Form1 : BaseLanguageForm
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.TriggerLanguageChange("fr-FR");
}
}
public class LanguageArgs : EventArgs
{
string _languageSymbol;
/// <summary>
/// Gets the language symble.
/// </summary>
public string LanguageSymbol
{
get { return _languageSymbol; }
}
/// <summary>
/// Initializes a new instance of the <see cref="LanguageArgs"/> class.
/// </summary>
/// <param name="symbol">The symbol.</param>
public LanguageArgs(string symbol)
{
this._languageSymbol = symbol;
}
}
public class BaseLanguageForm : Form
{
/// <summary>
/// Triggers the language change event.
/// </summary>
/// <param name="languageSymbol">The language symbol.</param>
protected void TriggerLanguageChange(string languageSymbol)
{
if (Form1.onLanguageChanged != null)
{
LanguageArgs args = new LanguageArgs(languageSymbol);
Form1.onLanguageChanged(this, args);
}
}
/// <summary>
/// This should be triggered whenever the combo box value chages
/// It is protected, just incase you want to do any thing else specific to form instacne type
/// </summary>
protected static event EventHandler<LanguageArgs> onLanguageChanged;
/// <summary>
/// This will be called from your form's constuctor
/// (you don't need to do anything, the base class constuctor is called automatically)
/// </summary>
public BaseLanguageForm()
{
//registering to the event
BaseLanguageForm.onLanguageChanged += new EventHandler<LanguageArgs>(BaseLanguageForm_onLanguageChanged);
}
/// <summary>
/// The function that was regidtered to the event
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void BaseLanguageForm_onLanguageChanged(object sender, LanguageArgs e)
{
string lang = e.LanguageSymbol;
foreach (Control c in this.Controls)
{
ComponentResourceManager crm = new ComponentResourceManager(typeof(Form1));
crm.ApplyResources(c, c.Name, new CultureInfo(lang));
}
}
}
There are two kinds of things you must translate: The controls that are visible on the form and the strings you you need during runtime to say, change a button's Text or a MessageBox's caption etc..
You translate the controls you have on the form in the designer:
First do all the layout stuff in the Laguage = Standard.
Then change the Languge in the properties tab to another language.
Now translate all Texts in all controls.
You also may need to change the layout a little to allow for longer texts; this is fine!
Look at the project explorer: For each form and for each language there is now a new FormN.lang.resx file, e.g:
Form1.resx
Form1.en.resx
Form1.de.resx
Now when you call a changeLanguage function, maybe like this one:
private void ChangeLanguage(Control ctl, string lang)
{
resources.ApplyResources(ctl, ctl.Name, new CultureInfo(lang));
foreach (Control c in ctl.Controls) ChangeLanguage(c, lang);
}
maybe like this:
private void cb_language_Click(object sender, EventArgs e)
{
if (cb_language.Text == "DE")
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE");
resources = new ComponentResourceManager(typeof(Form1));
ChangeLanguage(this, "de-DE");
cb_language.Text = "EN";
}
else
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
resources = new ComponentResourceManager(typeof(Form1));
ChangeLanguage(this, "en-US");
cb_language.Text = "DE";
}
}
..all visible controls will change their Texts.
The second thing to do is to create strings resource files, best one for standard and one for each language (repeating the standard values!): Add new element - resource file with names like these:
strings.resx
strings.de.resx
strings.en.resx
Then you add one name-value pair for each string you need in code, e.g:
msgCap_OW File Exists
msgTxt_OW Overwrite (Yes)
Use next free Index? (No)
Cancel?
cb_autoScrapeStart Start Timed Screenshots
Note: By shift-enter in a value field you can enter multiline values..
And finally you must change your code to use the strings resources, e.g. like this:
MessageBox.Show(strings.msgTxt_OW, strings.msgCap_OW, ..);
or:
cb_autoScrape.Text = (scrapeTimer.Enabled ?
strings.cb_autoScrapeStop : strings.cb_autoScrapeStart);

UltraGrid as UltraToolBar

What I need is a very custom situation.
I need to add UltraGrid to ultraToolbar as normal tool like buttontool.
Where I need to show customized tabular data.
I have tried to derive a userControl from ToolBase but somehow it didn't work.
I am attaching my code here. It has some errors.
FilterGrid.cs UserControl
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinToolbars;
using System.Runtime.Serialization;
using Infragistics.Win.UltraWinGrid;
using System.Security.Permissions;
using Infragistics.Shared.Serialization;
using Infragistics.Win.AppStyling;
namespace WindowsApplication1
{
public partial class FilterGrid : UserControl
{
public FilterGrid()
{
InitializeComponent();
}
[TypeConverter(typeof(FilterGrid.GridInternal))]
[Serializable()]
private class GridInternal : ToolBase
{
internal UltraGrid uGrid = new UltraGrid();
#region Constructors
public GridInternal(String key)
: base(key)
{
this.SharedProps.Width = 200;
this.SharedProps.ToolTipText = "FilterGrid";
this.SharedProps.DisplayStyle = ToolDisplayStyle.DefaultForToolType;
}
/// <summary>
/// Constructor used for de-serialization
/// </summary>
protected GridInternal(SerializationInfo info, StreamingContext context): base(info, context)
{
}
#endregion
#region Constants
internal static readonly string DEFAULTVALUE_CUSTOMPROP = "CustomValue";
#endregion Constants
#region Base Class Overrides
#region GetObjectData
/// <summary>
/// Called from our base class when ISerializable.GetObjectData is called. Serialize all custom property data here.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Call the base implementation
base.GetObjectData(info, context);
// Serialize our CustomProp property if necessary.
//if (this.ShouldSerializeCustomProp())
// Utils.SerializeProperty(info, "CustomProp", this.CustomProp);
}
#endregion GetObjectData
//#region ISerializable Members
//public void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// // Call the base implementation
// base.GetObjectData(info, context);
// // Serialize our CustomProp property if necessary.
// if (this.ShouldSerializeCustomProp())
// Utils.SerializeProperty(info, "CustomProp", this.CustomProp);
//}
//#endregion
#region Initialize
/// <summary>
/// Internal inherited method for initializing the tool when de-serialization completes.
/// Automatically called by toolbars manager.
/// </summary>
protected override void Initialize(ToolsCollectionBase parentCollection)
{
// Let the base do its processing.
base.Initialize(parentCollection);
// Use the temporary member variable to set the actual ExtraSharedProps properties.
// We need to wait until after deserialization is totally complete to ensure that
// our ExtraSharedProps object is properly setup.
//if (this.serializedProps != null)
//{
// this.ExtraSharedProps.customProp = this.serializedProps.customProp;
// this.serializedProps = null;
//}
}
#endregion Initialize
#region Clone
/// <summary>
/// Returns a cloned copy of the tool.
/// </summary>
/// <param name="cloneNewInstance">If true, returns a clone of the tool that can serve as an instance of the tool, sharing the same SharedProps object. If false, returns a tool that can be used as a new tool, with a clone of the original SharedProps object.</param>
/// <returns></returns>
protected override Infragistics.Win.UltraWinToolbars.ToolBase Clone(bool cloneNewInstance)
{
GridInternal tool = new GridInternal(this.Key);
tool.InitializeFrom(this, cloneNewInstance);
return tool;
}
#endregion //Clone
#endregion Base Class Overrides
#region CustomProp
/// <summary>
/// This is a custom property in a custom tool.
/// </summary>
//public string CustomProp
//{
// // Delegate the get/sets for the property to our ExtraSharedProps object
// get { return this.ExtraSharedProps.CustomProp; }
// set { this.ExtraSharedProps.CustomProp = value; }
//}
/// <summary>
/// Returns a Boolean value that determines whether the CustomProp property is set to its default value.
/// Checked during serialization to determine if the property should be serialized.
/// </summary>
internal protected virtual bool ShouldSerializeCustomProp()
{
// We only want to serialize the property if this tool is the Root tool and the
// property is not set to its default value.
return (this.IsRootTool);
}
#endregion CustomProp
protected override Type GetToolbarUIElementType()
{
return typeof(UltraGrid);
}
AccessibleRole rl = AccessibleRole.Pane;
UIRole roleOnMenus ;
UIRole roleOnRibbonGroups ;
UIRole roleOnToolbars;
protected override AccessibleRole DefaultAccessibleRole
{
get { return this.rl; }
}
protected override string DefaultAction
{
get { return "Get"; }
}
public override Infragistics.Win.AppStyling.UIRole UIRoleOnMenus
{
get { return this.roleOnMenus; }
}
public override Infragistics.Win.AppStyling.UIRole UIRoleOnRibbonGroups
{
get { return this.roleOnRibbonGroups; }
}
public override Infragistics.Win.AppStyling.UIRole UIRoleOnToolbars
{
get {return this.roleOnToolbars; }
}
}
private void DrawFilter(UltraToolbarsManager tbm)
{
GridInternal gdInternal = new GridInternal("gridInternal");
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Rows.Add(new object[] { "MyRow"});
gdInternal.uGrid.DataSource = dt;
gdInternal.SharedProps.Caption = "FilterGrid";
Infragistics.Win.UltraWinToolbars.StateButtonTool stb = new StateButtonTool("isEnabled");
stb.SharedProps.DisplayStyle = ToolDisplayStyle.ImageAndText;
stb.SharedProps.CustomizerCaption = "Enable";
stb.SharedProps.Caption = "Enable";
Infragistics.Win.UltraWinToolbars.LabelTool lb = new LabelTool("FilterStatus");
lb.SharedProps.Caption = "FilterStatus";
Infragistics.Win.UltraWinToolbars.StateButtonTool filterstb = new StateButtonTool("Applied");
filterstb.SharedProps.DisplayStyle = ToolDisplayStyle.ImageOnlyOnToolbars;
filterstb.SharedProps.CustomizerCaption = "Applied";
filterstb.SharedProps.Caption = "Applied";
Infragistics.Win.UltraWinToolbars.LabelTool lb1 = new LabelTool("SetFilterType");
lb1.SharedProps.Caption = "SetFilterType";
Infragistics.Win.UltraWinToolbars.ComboBoxTool cbTool = new ComboBoxTool("FilterList");
cbTool.SharedProps.Caption = "FilterType";
cbTool.DropDownStyle = Infragistics.Win.DropDownStyle.DropDownList;
Infragistics.Win.ValueList vl = new Infragistics.Win.ValueList();
cbTool.ValueList.ValueListItems.Add("Select");
cbTool.ValueList.ValueListItems.Add("List1");
cbTool.ValueList.ValueListItems.Add("List2");
cbTool.ValueList.ValueListItems.Add("List3");
cbTool.ValueList.ValueListItems.Add("List4");
cbTool.SelectedIndex = 0;
Infragistics.Win.UltraWinToolbars.ButtonTool btReset = new ButtonTool("Reset");
btReset.SharedProps.DisplayStyle = ToolDisplayStyle.ImageAndText;
btReset.SharedProps.Caption = "ResetFilters";
tbm.Tools.AddRange(new ToolBase[] { stb, lb, filterstb, lb1, cbTool, btReset, gdInternal });
UltraToolbar tb = new UltraToolbar("Filter");
tbm.Toolbars.AddToolbar("Filter").Tools.AddToolRange(new String[] { "isEnabled", "FilterStatus", "Applied", "SetFilterType", "FilterList", "Reset", "gridInternal" });
// tb.Tools.AddTool("isEnabled");
}
public FilterGrid(UltraToolbarsManager tbm):this()
{
DrawFilter(tbm);
}
}
}
Main.cs main form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
FilterGrid fg = new FilterGrid(ultraToolbarsManager1);
}
}
}
EDIT
I want to derive a control from Toolbase and show it on UltraToolbar, if it is possible.
Now I got how to do that.
I created an instance of controlContainerTool and assign my ultragrid to it.
controlContainerTool is added to UltraToolbarsManager and toolbar instance too.
Appearance can be set at design time from code.
One most important thing is to handle scrollbar in the grid if gets larger than expected.

Categories

Resources