Telerik Reports parameters from WindowsForm Codebehind to Report - winforms

I'm working on a Windows Forms Application where I want to load Reports into a Reportviewer after a click on a Button.
This is the Event that gets triggered by pressing on the button in the Code behind of the Windows Form:
private void button1_Click(object sender, EventArgs e)
{
Telerik.Reporting.InstanceReportSource reportSource = new
Telerik.Reporting.InstanceReportSource();
reportSource.ReportDocument = new Reportlibrary.Report1();
reportSource.Parameters.Add(new Telerik.Reporting.Parameter("OrderNumber","123456789"));
reportViewer1.ReportSource = reportSource;
reportViewer1.RefreshReport();
}
The problem now is that I have no Idea how I can access / get the parameter I added before Refreshing the Reportviewer.
The Report already has set a Datasource. I don't know if this matters.
This is what I have right now. I've tried everything and I'm just not getting further.
public Report1()
{
InitializeComponent();
Position[] all = new Position[]{
new Position("Test", "Test","test"),
};
this.DataSource = all;
MessageBox.Show("Number: " +
this.Report.ReportParameters["OrderNumber"].Value.ToString());
}
Is there any way to get this parameter straight after InitializeComponent(); ?
Do I need to add another Event to the report to access it? If yes which on is the best way to do this?
Any help very apreciated.
Thank you

Set the parameters of the report on an instance of the report itself (not the report source), such as:
TopPageViews report = new TopPageViews();
report.ReportParameters["StartDate"].Value = new DateTime(2013, 3, 1);
report.ReportParameters["EndDate"].Value = new DateTime(2013, 3, 1);
InstanceReportSource reportSource = new InstanceReportSource();
reportSource.ReportDocument = report;
this.reportViewer1.ReportSource = reportSource;
this.reportViewer1.RefreshReport();
In your report constructor, after InitializeComponent, subscribe a handler to the ItemDataBinding event:
this.ItemDataBinding += TopPageViews_ItemDataBinding;
And in your handler, you can obtain the value as you normally would:
DateTime startDateParm = (DateTime)this.ReportParameters["StartDate"].Value;
You can use the debugger to see the value.

i know its an old question but after experiencing the same issue this how i did it and passed two parameter of date.
private void button1_Click(object sender, EventArgs e)
{
Report2 report = new Report2();
report.ReportParameters["datefrom"].Value
=dateTimePicker1.Value;
report.ReportParameters["dateto"].Value = dateTimePicker2.Value;
var rSource = new InstanceReportSource();
rSource.ReportDocument = report;
reportViewer1.ReportSource = rSource;
reportViewer1.RefreshReport();
}

Related

Windows Phone Navigation - Passing back to the page before

I would like to click on a button to take me to a page
, then click on a listbox item, click on a button on the new page and pass it back to the page before without creating a new URI of the first page.
**First Page**
private void btnAddExistingMember_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/ChooseMember.xaml", UriKind.Relative));
}
**Second page after choosing listbox value**
private void btnAddSelected_Click(object sender, RoutedEventArgs e)
{
Member currMember = (Member)lstMembers.SelectedItem;
string memberID = currMember.ID.ToString();
//navigate back to first page here passing memberID
}
can it be done?
Thank you
You can store the member in the App.xaml.cs file. This is common file accesssible for all files in the application.
This works like a global variable.
//App.xaml.cs
int datafield ;
//Page1xaml.cs
(App.Current as App).dataField =10;
//Page2.xaml.cs
int x = (App.Current as App).dataField
You could create a manager class that would hold the member id. This manager class could then be accessed from both your first page and ChooseMember page.
An example of a Singleton Manager class :-
public class MyManager
{
private static MyManager _instance;
public static MyManager Instance
{
get
{
if (_instance == null)
{
_instance = new MyManager();
}
return _instance;
}
}
}
I found a solution at codeproject which was quite useful to me.
While moving from the second form, save your data in PhoneApplicationService.Current.State
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
// Called when a page becomes the active page in a frame
base.OnNavigatedFrom(e);
// Text is param, you can define anything instead of Text
// but remember you need to further use same param.
PhoneApplicationService.Current.State["Text"] = txtboxvalue.Text;
}
Go back using same NavigationService.GoBack(); and in OnNavigatedTo method, fetch the following code.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (PhoneApplicationService.Current.State.ContainsKey("Text"))
txtvalue.Text = (string)PhoneApplicationService.Current.State["Text"];
}
References:
MSDN: PhoneApplicationService Class
Original Solution at: How to pass values between pages in windows phone
Sounds to me like you want to set some object as the context for another page. Messaging in MVVM Light sounds like a good solution for this. Doesn't look like you're using MVVM so this may not be immediately applicable. This post pretty much lays out what I'm saying here.
Second Page
Create your SelectedObject property and make sure to call
RaisePropertyChanged(SelectedObjectPropertyName, oldValue, value, true);
The last parameter true says to broadcast this change in value to anyone listening. You'll need to wire up some other commands for listbox selected item and button click etc, but I won't go into that here since it's not directly related to your question. Selecting the Listbox item will simply set the data item for the first page like you want to accomplish. The button click can deal with the navigation.
First Page
In your view model constructor, register to receive the change broadcasted from Second Page
Messenger.Default.Register<PropertyChangedMessage<MyObject>>(this, (action) => UpdateObject(action.NewValue));
then define UpdateObject
private void UpdateObject(MyObject newObject)
{
LocalObjectProperty = newObject;
}
You can simply use
//first page
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string value = string.Empty;
IDictionary<string, string> queryString = this.NavigationContext.QueryString;
if (queryString.ContainsKey("memberID"))
{
memberID = queryString["memberID"];
if (memberID != "-1")
//your code here
}
base.OnNavigatedTo(e);
}
//second page
private void btnAddSelected_Click(object sender, RoutedEventArgs e)
{
Member currMember = (Member)lstMembers.SelectedItem;
string memberID = currMember.ID.ToString();
string target = "/FirstPage.xaml";
target += string.Format("?memberID={0}", memberID);
NavigationService.Navigate(new Uri(target, UriKind.Relative));
}

Detect when a row is edited in a DataGrid

I've been trying to google this but have been unable to find a solution that works for me.
I have a DataGrid that is displaying some info from a SQL table that the client dosn't know about.
The client just sends a request to the server and gets a List<SomeClass> as a response that it then displays in a DataGrid.
I need to detect when the user makes change to a row and I need the new values that the user entered.
Currently I'm using RowEditEnding event. And the method that handles this event can then:
private void editRowEventHandler(object sender, DataGridRowEditEndingEventArgs e)
{
SomeClass sClass = e.Row.DataContext as SomeClass;
// Send sClass to the server to be saved in the database...
}
This gives me the row that was being edited. But it gives me the row before the changes, and I'm unable to figure out how to get the row after the changes happen.
Is there anyone here that knows how I can do this or can point me in a direction where I might be able to find out?
See the discussion here, to avoid reading out cell-by-cell.
private void OnRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
if (e.EditAction == DataGridEditAction.Commit) {
ListCollectionView view = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource) as ListCollectionView;
if (view.IsAddingNew || view.IsEditingItem) {
this.Dispatcher.BeginInvoke(new DispatcherOperationCallback(param =>
{
// This callback will be called after the CollectionView
// has pushed the changes back to the DataGrid.ItemSource.
// Write code here to save the data to the database.
return null;
}), DispatcherPriority.Background, new object[] { null });
}
}
}
In your case, you are trying to detect the change in object. It comes down to the properties of the SomeClass, thus you need to focus on "Cell" instead of "Row"
Assuming your datagrid is resultGrid, i come up with the below code:
resultGrid.CellEditEnding += resultGrid_CellEditEnding;
void resultGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
var yourClassInstance = e.EditingElement.DataContext;
var editingTextBox = e.EditingElement as TextBox;
var newValue = editingTextBox.Text;
}
the "e" also contains information about Row and Column of the Cell. Thus you will know which editor the cell is using. In this case, i assume that it is a textbox.
Hope it help.

Connecting 2 Textboxes values temporarily

I want to create 2 Textboxes (txt1, txt2) and when I write in txt1 then txt2 should reflect the same text what i typed in txt1. For ex. When we create a new Solution in Visual Studio Professional, what name we give to Project, same name appears for Solution. But if we edit solution name, link between the 2 textboxes breaks.
I do have some idea about it, to do it with textChange event or in fact many similar events, but not sure that they are the best methods.
I am using Winforms, C# 4.0, Visual Studio 2010 (if this info matters)
If my question is not clear, just make a comment I will try to elaborate.
Thanks.
With the given definition of the requirement, adding TextChanged EventHandlers is the way to go.
private void txt1_TextChanged(object sender, EventArgs e)
{
txt2.Text = txt1.Text;
}
private void txt2_TextChanged(object sender, EventArgs e)
{
txt1.Text = txt2.Text;
}
Consider adding an event handler for txt1_TextChanged and txt2_KeyPress.
txt1_TextChanged would assign txt2.Text: txt2.Text = "c:\" + txt1.Text;
txt2_KeyPress would unsubscribe txt1_TextChanged: txt1.TextChanged -= txt1_TextChanged;.
I solved it, so thought to post it here
txt1_TextChanged(obje....)
{
txt2.Text = txt1.Text;
}
txt2_TextChanged(objec...)
{
if(txt2.Focused)
{
txt1.TextChanged -= new EventHandler(txt1_TextChanged);
}
}
Hope it helps.

Silverlight, connecting service.cs and XAML.cs for database

I've found a sample showing how to connect to SQL server (a local MDF), but it uses databinding, how can I use SQL in the normal way (insert, select, update, delete..., sqldatareader, without binding), I think all SQL staff should be performed in service.cs, so how can I use SQL from my XAML.cs? here is the service code:
and here service.cs:
public class ServiceCustomer : IServiceCustomer
{
public clsCustomer getCustomer(int intCustomer)
{
SqlConnection objConnection = new SqlConnection();
DataSet ObjDataset = new DataSet();
SqlDataAdapter objAdapater = new SqlDataAdapter();
SqlCommand objCommand = new SqlCommand("Select * from Customer where CustomerId=" + intCustomer.ToString());
objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
objConnection.Open();
objCommand.Connection = objConnection;
objAdapater.SelectCommand = objCommand;
objAdapater.Fill(ObjDataset);
clsCustomer objCustomer = new clsCustomer();
objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
objConnection.Close();
return objCustomer;
}
}
and my page.xaml.cs:
public Page()
{
InitializeComponent();
ServiceCustomerClient obj = new ServiceCustomerClient();
obj.getCustomerCompleted += new EventHandler<getCustomerCompletedEventArgs>(DisplayResults);
obj.getCustomerAsync(1);
}
void DisplayResults(object sender, getCustomerCompletedEventArgs e)
{
LayoutRoot.DataContext = e.Result;
}
how can I insert a value into my dayabase right from my page.xaml.cs? how can I make a connection between service and xaml objects and functions?
thanks
The Page.xaml.cs file is not autogenerated in a standard silverlight project (beyond it's initial creation via template), so any changes you make to the class will persist.
If your current project does some autogen of xaml classes then you can use the partial class feature of C# Partial Classes in C# Guide to add to the class without worrying that the autogen will remove your additions.
You would need to add another method within your service class that performs the insert, and then pass it the values from your form.
public class ServiceCustomer : IServiceCustomer
{
public clsCustomer getCustomer(int intCustomer)
{
...
}
public void addCustomer(clsCustomer newCustomer)
{
//Code to add the customer to the database
}
}
to call this from your code you could use the following code, all calls to the service in silverlight are Asynchronous calls therefore they are called in a seperate thread but since the following call has no return there is no need for a completed event handler.
public void foo
{
clsCustomer cust = new clsCustomer();
//Create your customer object here
ServiceCustomerClient obj = new ServiceCustomerClient();
obj.AddCustomerAsync(cust);
}
this function could then be called when ever you want to add a customer, E.g. when a button is clicked
public void somebutton_Click(object sender, RoutedEventArgs e)
{
foo();
}
If you need any more information let me know.

Failing to display a custom WPF dialog box more than one time

I am trying to display a custom dialog box multiple times using the following code:
TestWindow newTestWindow = new TestWindow(test);
newTestWindow.Owner = this;
newTestWindow.ShowDialog();
And I get the following exception when running the code above for the 2nd time:
Specified element is already the logical child of another element. Disconnect it first.
Chances are you are trying to display the same element in both dialogs (maybe the test parameter)? You would need to disconnect the element from the dialog when it's closed, so that it can be used in any subsequent dialogs.
Works fine for me:
public partial class MainWindow : Window
{
private Test _newTestWindow;
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(OnLoaded);
}
private void OnLoaded( object sender, RoutedEventArgs e )
{
_newTestWindow = new Test { Owner = this };
_newTestWindow.ShowDialog();
_newTestWindow = new Test { Owner = this };
_newTestWindow.ShowDialog();
}
}

Resources