26 June 2012

Invoke custom method in Crystal report default print button click event


We have requirement is when i click on default crystal report print button, it will open printoptions window, when i select/click the Ok button, on button click event i want to insert data into the database(Call custom method). we tried so many way at last we got the solution for that as shown in bellow link
My Link: http://dotnetgoutham.blogspot.in/2012/06/get-control-name-in-pageload-event.html
Step 1:
 public string GetPostBackControlId(Page page)
    {
        if (!page.IsPostBack)
            return string.Empty;


        Control control = null;
        // first we will check the "__EVENTTARGET" because if post back made by the controls
        // which used "_doPostBack" function also available in Request.Form collection.
        string controlName = page.Request.Params["__EVENTTARGET"];
        if (!String.IsNullOrEmpty(controlName))
        {
            control = page.FindControl(controlName);
        }
        else
        {
            // if __EVENTTARGET is null, the control is a button type and we need to
            // iterate over the form collection to find it


            // ReSharper disable TooWideLocalVariableScope
            string controlId;
            Control foundControl;
            // ReSharper restore TooWideLocalVariableScope


            foreach (string ctl in page.Request.Form)
            {
                // handle ImageButton they having an additional "quasi-property" 
                // in their Id which identifies mouse x and y coordinates
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    controlId = ctl.Substring(0, ctl.Length - 2);
                    foundControl = page.FindControl(controlId);
                }
                else
                {
                    foundControl = page.FindControl(ctl);
                }


                if (!(foundControl is Button || foundControl is ImageButton)) continue;


                control = foundControl;
                //hdPrintValue.Value = control.ID;
                Session["HiddenValue"] = ctl.Substring(ctl.Length - 7, 5);
                break;
            }
        }
        return control == null ? String.Empty : control.ID;
    }
Step 2:
        string str = GetPostBackControlId(this.Page);
        if (Session["HiddenValue"] != null)
        {
            if (Session["HiddenValue"].ToString() == "ctl01" && str == "CrystalReportViewer1")
            {
                //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowMessage", "alert('Updated Successfully');", true);
                try
                {
                    //Call custom Method() here....
                }
                catch (Exception ex)
                {
                   
                }
            }
        }

Get control name in Page_Load event which make the post back



Need to know which specific control posted back to your page? (Original article at http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx)
/// <summary>
/// Gets the ID of the post back control.
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
    if (!page.IsPostBack)
        return string.Empty;
    Control control = null;
    // first we will check the "__EVENTTARGET" because if post back made by the controls
    // which used "_doPostBack" function also available in Request.Form collection.
    string controlName = page.Request.Params["__EVENTTARGET"];
    if (!String.IsNullOrEmpty(controlName))
    {
        control = page.FindControl(controlName);
    }
    else
    {
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it
        // ReSharper disable TooWideLocalVariableScope
        string controlId;
        Control foundControl;
        // ReSharper restore TooWideLocalVariableScope
        foreach (string ctl in page.Request.Form)
        {
            // handle ImageButton they having an additional "quasi-property" 
            // in their Id which identifies mouse x and y coordinates
            if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
            {
                controlId = ctl.Substring(0, ctl.Length - 2);
                foundControl = page.FindControl(controlId);
            }
            else
            {
                foundControl = page.FindControl(ctl);
            }


            if (!(foundControl is Button || foundControl is ImageButton)) continue;


            control = foundControl;
            break;
        }
    }
    return control == null ? String.Empty : control.ID;
}


If you are using master pages, simply add this to the master.cs file and where you need to call the method use the following code:
MasterPage masterPage = (MasterPage)Page.Master; // where MasterPage is the class name
 Control rep = masterPage.getPostBackControlName();
 if (rep.Parent.Parent.ID == "rpRegion")// only if postback is the regions control
 GetSelectedRegion();

08 June 2012

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>). 
Use <%# this.txtCompany.ClientID %> to replace <%= this.txtCompany.ClientID %> to fix the problem.

Once those changes are done then run the application if your not getting the values of controls(getting balnk ("") value instead of Client id) then follow the below step.

Re-place (<%# ... %>) with (<%= ...%>) and put your script from "head" tag to "body" tag.


Ref Link:- 
http://www.west-wind.com/weblog/posts/2006/May/27/The-Controls-collection-cannot-be-modified-because-the-control-contains-code-blocks-ie-
http://www.dotnet-tips.com/2006/09/controls-collection-cannot-be-modified.html

30 May 2012

Temporary table issue in RDLC

I have just created a RDLC report using a Stored Procedure, which uses a temporary table.  I am getting error "Could not generate a list of fields for the query. Invalid object name '#Tablename'".  To fix this add below statement in Stored Procedure before creating temporary tables.
"SET FMTONLY OFF"
Make your temp table a permanent one and do the management of it yourself (deleting rows after use etc). This could be faster as well as indexable and you can add keys as needed to ensure integrity. It can also act as a cache for long running queries.


18 May 2012

Data Cache in ASP.NET

Most of the times we need to store large amounts of data client side is by using the ViewState. It will only exist on the page you add it to though. So if you are jumping around from page to page it won't really work. In that case you really should be using Session or Application Cache depending on your scenario.


ViewState:  
 ViewState is one of the techniques that Asp.net provides in order to save the data for latter use. The important fact about the ViewState is that it can only save the values for page level access. It means that if I save something on page1.aspx using Viewstate I cannot access it on the page2.aspx using the same technique. For this reason ViewState is only used to save the values for the page level access which should be maintained after post backs.Whenever we write anything in the ViewState object a hidden field is created in the page. After the post back it will display the value of the dataset using the ViewState control.

So if you are doing something where you are always on the same page and just doing many PostBacks for things like paging or sorting then ViewState will work fine but do realize you will be passing large amounts of data back and forth to the server each time a PostBack is made.
Example Using ViewState:

// Set it
ViewState["dsViewEmp"] = dsEmployee;


// Get it
DataSet ds = ViewState[" dsViewEmp "] as DataSet;


Session and the Application Cache are accessed the same way. Just replace ViewState with the word Session or Cache.


What is Data Cache?
Data Cache is used to storing frequently used data in the Cache memory. It's much efficient to retrieve data from the data cache instead of database or other sources. We need use System.Web.Caching namespace. The scope of the data caching is within the application domain unlike "session". Every user can able to access this objects.


How data caching is work?
When client request to the server, server execute the stored procedure or function or select statements on the Sql Server database then it returns the response to the browser. If we run again same process will happen on the web server with sql server.
In the very first time retrieve the records from the sql server database and stored into the Cache memory.  After that records will retrieve from Cache memory (IIS). We can set expiration period time after expiration time over the caching again it will hit the sql server database and stored into the cache memory and next retrieve will happen on the data cache memory.


Advantages of Cookies
Following are main advantages of using cookies in web application:
It's very simple to use and implement.
We can avoid database hitting.
We can reduce network traffic.

How to create data cache? 
Cache["Employee"] = dsEmployee


We can create data caching use Cache Keyword. It's located in the System.Web.Caching namespace. It's just like assigning value to the variable


How to Read data from Data Cache?
Dataset dsEmployees = (Dataset) Cache ["Employee"]


This is very similar to assigning object to the Dataset.


Where does Data Cache are stored?
This is one of the interesting things to find out the Data Caching in your local drive. First of all, From "IE Internet Option ", delete Browsing History to clear Cache. 


How to remove a Data Cache? 
We can remove Data Cache manually.

//We need to specify the cache name


   Cache.Remove(String key);



Conclusion:
When it comes to choosing between ViewState and Caching it all comes down to what you are doing. ViewState is an ideal candidate if you are planning to save small values. Mostly values of server controls are saved in ViewState. If you plan to store large datasets, datatables or collections than data caching is an excellent candidate.


ReferenceLinks:
1. http://www.highoncoding.com/Articles/69_View_State_vs_Data_Caching.aspx
http://msdn.microsoft.com/en-us/library/z1hkazw7%28VS.80%29.aspx






05 May 2012

Using MID() to Cut Out a SubString

I have a filed that begins with numeirc characters and it ends with alpha character (like 0125461E). I want to alpha (E) part form the string and leave the remaining (0125461) field value.

we need to "cut" it out of our  IDNumber field.
Our example field is called {USERS. IDNumber}.
Now the way we cut strings out of other strings is with the MID() function. The MID function takes three parameters. The string on which to operate, where to start and the length of the string to return.

MID(String, Starting Character Position, Length of String to Return)

Supposing that {USERS. IDNumber } is going to return Justin Hill, we can see the result of various MID statements:
MID({USERS. IDNumber }, 8, 1) then we will get "E"
Also note that you may omit the final parameter (length) to return "the rest" of the string, like this:
MID({USERS. IDNumber  }, 8) 

Example:

//Declaring variable to display message...
Stringvar message;
if (MID({REP. IDNumber},  8 ,1)="E")
then message:="Employee" 

Pass value from main report to sub report

I am designing a report which includes sub report every thing is fine but i have to display the main report field value in sub report . To get the main report vale in to the sub report follow the bellow steps.
Step 1:
1. In main report create a formula, name it, edit it with the formula editor as follows:
Shared numbervar NAME := {Rep.Sno} 
Save formula.  Note that you should replace the name and type of variable and a formula with ones of your own
2. Now create a formula in your subreport, name it, edit it with the formula editor as follows:

Shared numbervar NAME;
NAME
3. Use formula created in step 2 in your report (drag drop in the report from formula fields.
Note that subreport is processed after the main report, so it's easier to pass values from main report to subreport.

01 May 2012

Display a serial number in RDLC report

I have developed a report in reportviewer using ASP.NET. I want to display serial number in report follow the below steps. In RDLC design drag and drop a text box from the toolbox and right click on it and select Expression as shown below.


An expression containing the RowNumber function, when used in a text box within a data region, displays the row number for each instance of the text box in which the expression appears. This function can be useful to number rows in a table.
Using RowNumber(Scope) function to display the row numbers. If scope is nothing then RowNumber(Nothing) provides the running count of rows in the outermost data region.

How to Change Date Format in .RDLC reports (MM/dd/yyyy)

In my Report Design i want to show date in the format of (MM/dd/yyyy). The column has the value in dd/MM/yyyy.  The output on the webform looks like this: 05/18/2012 to do this follow the below steps.
Step1: In RDLC design right click on the column/textbox and then it will open context menu as shown below then select the Expression option from the menu.
Step 2:When click on Expression then it will open a windows as shown below. Change the Expression statement as shown and then click on OK button.


RDLC report Text box/Column value formating

In my RDLC reports i want show 2 decimal points. Decimal value like 25.5000 now i want to show it in 2 decimal point in report (25.50). To do as shown below.
Use the "Round" function on your column or Textbox.
Some thing like  =Round(FieldName,2) 
where FieldName is the name of your column or the value you want to round off and 2 is the decimal places

Time Out downloading large files

When your downloading a table data in the format of excel sheet, while doing that it throws time out error due to lack of enough size. To download the file add the following tag in the web.config file as shown below.
Problem:

By default, Machine.config is configured to accept HTTP Requests upto 4096 KB (4 MB) and it is reflected in all your ASP.NET applications. You can change the Machine.config file directly, or you can change only the Web.config file of the application(s) you want to.
Open your Web.config file, and just below the <system.web> tag, add the following tag:

  <system.web>
    <httpRuntime executionTimeout="90"
            maxRequestLength="4096"
            useFullyQualifiedRedirectUrl="false"
            minFreeThreads="8"
            minLocalRequestFreeThreads="4"
            appRequestQueueLimit="100"
            enableVersionHeader="true"
    />
Now, just take a look at the maxRequestLength="4096"  and   executionTimeout="1000" attribute of the  <httpRuntime>  tag. As you may have realized, all you need to do is change the value to some other value of your choice (8192 for 8 Mb, 16384 for 16 Mb, 65536 for 64 Mb, and so on...).

17 April 2012

MS Chart Legend Properties and Hide Series Based on Condition

I have a MSChart that displays two series. The data is taken from a database. Sometimes I only want to display one of the series in my chart based on the condition. Follow the bellow steps to hide series.
                 Chart1.Series["Series Name"].Enabled = false; 


We can set Legends properties in code behind as shown bellow steps.
                Chart1.Legends["Default"].Title = "Chart";
                Chart1.Legends["Default"].LegendStyle = LegendStyle.Column;
                Chart1.Legends["Default"].Docking = LegendDocking.Right;
                Chart1.Legends["Default"].Alignment = StringAlignment.Center;
                Chart1.Legends["Default"].BackColor = System.Drawing.Color.Transparent;
                Chart1.Legends["Default"].IsTextAutoFit = false;
                Chart1.Legends["Default"].BorderColor = Color.Black;
                Chart1.Legends["Default"].BorderWidth = 2;
                Chart1.Legends["Default"].BorderDashStyle = ChartDashStyle.Solid;
                Chart1.Legends["Default"].Font = new Font("Arial", 10, FontStyle.Bold);
                Chart1.Legends["Default"].ForeColor = Color.Black;
                Chart1.Legends["Default"].IsEquallySpacedItems = true;


We can set Legends properties in Design 

<Legends>
     <asp:Legend Name="Legend1" Docking="Right" Title="Chart" ForeColor="Black" BorderColor="Black" BorderWidth="2"  BorderDashStyle="Solid" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"  IsTextAutoFit="False">
     </asp:Legend>
</Legends>

05 April 2012

Comparing ListView with GridView,DataList and Repeater

ASP.NET 3.5 introduces a new data binding control named the ListView. ASP.NET already has a lot of data bind controls; it should be more than 10. But the good news is, ListView can literally replace all other data binding controls in ASP.NET. ListView control makes data binding easier than previous controls. It has included styling with CSS, flexible pagination, and sorting, inserting, deleting, and updating features.

  1. A very flexible and customizable layout.
  2. A built in data paging support with the new DataPager control.
  3. Support data grouping (repeating items) in a flexible way.
  4. Built in support for deleting,inserting,paging,sorting,and updating the data.
Now , to compare the ListView control with the dataList,GridView and repeater control , lets look at the table below : 

Supported Funcationalities
ControlPagingData GroupingProvide Flexible LayoutUpdate,DeleteInsertSorting
ListViewsupportedsupportedsupportedsupportedsupportedsupported
GridViewsupportedNot supportedNot SupportedsupportedNot Supportedsupported
DataListNot supportedsupportedsupportedNot supportedNot supportedNot supported
RepeaterNot supportedNot supportedsupportedNot supportedNot supportedNot supported
* Supported: means that it's provided out of the box without any custom code or hacks.
* Not Supported: means that it's not provided out of the box by the control but it could be possible to implement it using custom code \ hacks.
The GridView : it supports paging but it doesn't provide a flexible layout , since its mainly used to display the data in a table based layout.And If we looked at data inserting , the Gridview doesn't have a built in support for inserting data( since it doesn't call the insert method of it underlying data source when you click on a button with a CommadName set to "Insert" ).
The DataList : it support data grouping ( through its RepeatColumns property) , but it doesn't have a built in support for paging,inserting ,deleting , updating the data. and if you looked at its laout , you will find that by default  the datalist renders as html table and you will have to set its flowLayout to "Flow" to stop that behaviour.
The Repeater control : you will find that it provides a flexible layout but it doesn't support data grouping ,inserting,deleting , updating  and paging through the data .

31 March 2012

Convert String to Number in Crystal Reports

Use a Crystal formula to convert string field to Number by using the ToNumber function.
Example: 
ToNumber({Table.Column})


To convert any Numeric field to Text by using the ToText function.
Example:
ToText({Table.Column})
This will allow you to use String functions (i.e. Mid, Left, etc) on any Numeric field.

Hide fields in Crystal Report

To hide any formula value or field values.  Select field and right click on it then context menu displays select Format Editor as shown below screen shots.
Step 1:
Step 2:

20 March 2012

Using Session State in a Web Service

In my web application i have used web services many time. Now i need to pass session variable to the web service method to get data form the database based on the session value. When i am passing session value I got an error. After searching i found the solution to use HttpSession in web methods. It is very simple to resolve this issue i.e enable the session state before using it. This can be done by using following attribute.
[WebMethod(EnableSession=true)] //C#
<WebMethod(EnableSession:=true)] 'VB.net

Example: 
Passing Session value
Session["Value"] = 3; 
Access this session variable (Session["Value"] ) in Add Web Method.
Example:

[WebMethod(Description = "adds x , y and  Value session")]
public int Add(int x, int y)
{
   return (x + y) + (int)Session["Value"] ;
}
This will not work and throws an error. To avoid this needs to enable session state in each web metods.
Example:
[WebMethod(EnableSession = true, Description = "adds x , y and  Value session")]
public int Add(int x, int y)
{
return(x + y) + (int)Session["Value"] ;
}
Once you specify these lines over your web method you can use the session object naturally.

19 March 2012

C# - Error: Could Not Load File Or Assembly 'Microsoft.ReportViewer.WebForms, Version=9.0.0.0

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Solution 
This error means you're using the SQL Server Reporting Services/Crystal Reports  ReportViewer control in your web application, and the server can't find the proper DLL. All you have to do is deploy them to your server. With Visual Studio 2008, the location of the ReportViewer DLLs has changed. 
You now find them at C:\Program Files\Microsoft Visual Studio 9.0\ReportViewer.
The first way to get these on your server, and this only works if you run your own server, is to directly copy them into the C:\Windows\assembly folder, and reboot the server (this reloads the GAC). If a reboot is out of the question, you can use GACUTIL.EXE to copy and register the DLLs. 
If you're in a shared hosting environment, reference the DLLs from the VS 9 path listed above, and set the Copy Local=True (select the DLL and open the Properties tab). This will copy the DLLs into your applications BIN folder, and look for them there first. You can then deploy to a shared host, making sure to copy all the contents of BIN.


Dll name 
paste following dll in bin folder or windows folder
1> Microsoft.ReportViewer.Common.dll
2> Microsoft.ReportViewer.ProcessingObjectModel.DLL
3> Microsoft.ReportViewer.WebForms.dll
4> Microsoft.ReportViewer.WinForms.dll

13 March 2012

Windows 7, IIS 7.5 Images, CSS not showing!

Web site having ASP.NET themes. Theme including a CSS file in it, the CSS file was linked in the generated HTML but clearly it was not applied. Putting the URL of the CSS file in the browser address bar would return an empty result in Firefox, and a crappy DOCTYPE,HTML,HEAD,BODY tags in IE. The same website works normally with other developers running Windows XP or Windows 7.
I tried change the website from custom Application Pool to default integrated pipeline one to default classic (IIS 6 like) one, but no use.
Here’s what the problem was:  
While installing IIS 7.5 for the first time, needed to choose  “Static Content” checked as well to display images in the website. 

28 February 2012

This BackgroundWorker states that it doesn't report progress/cancellation. Modify WorkerReportsProgress to state that it does report progress.

Error Type1:  This BackgroundWorker states that it doesn't report progress. Modify WorkerReportsProgress to state that it does report progress.
The error occurs when the WorkerReportsProgress of the background worker is not set to true.

This should be set (to True ) from the properties window as shown below screen.

Error Type 2: This BackgroundWorker states that it doesn't support cancellation. Modify WorkerSupportsCancellation to state that it does support cancellation
The error occurs when the WorkerSupportsCancellation of the background worker is not set to true.
This should be set (to True ) from the properties window as shown below screen.


Using Background Worker in C#

Most of our application that we develop today require simultaneous functions to perform but with performance.  Working with Microsoft .NET framework we have worked with threads through which we can handle all the tasks simultaneously under one main application thread. You can perform smaller operations with the help of Threading class, instead I prefer using Background Worker class to implement to perform all my heavy duty operations.
Background worker class is introduced in .NET framework 2.0 and using this class makes it easy to execute long running operations on a separate thread, support cancellation, progress reporting and marshalling results back to the UI thread.
Now we will see how to use background worker class to perform heavy operations.
My requirement is execute more than one form code simultaneously. Each form, connect to the database and start the execution back end it takes more than one day. Each form will behave same.  To do this i have choose Back Ground Worker.  
I have four buttons to open four forums when i click each one them, a new window will open and then i will start the execution of functionality.
Now let start working with BackgroundWorker.
Create four forms as shown bellow.

First, you need an instance of BackgroundWorker class,Get to the design mode and drag & drop the background worker component on form,  form Component tab of Toolbox as shown bellow screen.
Set the properties of the background worker:
Set GenerateMember and Modifiers as it is. In the sample application we have a progress bar which reports the percentage of the task completed so we need to set the WorkerReportsProgress to true and similarly if we want the user to cancel the running operation then set the WorkerSupportsCancellation to true.

Now the next step is to create 3 event methods:
1.) DoWork: This is the main method which is responsible to handle the large operation. The code here is not different than the usual code.
2.) ProgressChanged: This method reports the change in the progress of the operation performed by the background worker DoWork method.
3.) RunWorkerCompleted:Thismethod checks the RunWorker Completed Event Args and perform action accordingly.
Starting with the Start button:
Next step is to set the event handlers of you object, and finally you have to call RunWorkerAsync() method.  Whenever you call this method it get a free thread from CLR and fires DoWork event. Now you put your codes (The codes that you want to be executed in another thread) in event handler of DoWork event. If the code completed it will raise an event called RunWorkerCompleted to notify you. It 's important to know that this event is not raised on the new thread instead, it will be raised on main thread of your application.

private void btn_start_Click(object sender, EventArgs e)
{
//Starts the backgroundworker process asynchronously
backgroundWorker1.RunWorkerAsync();
btn_start.Enabled = false;
} 
The DoWork method: 
The event args of DoWork event is an object of type DoWorkEventArgs.
In this object you have a property called Argument for getting what you have passed in RunWorkerAsync() method. You can use it in your time-consuming task. 
//Background worker DoWork method. Here we will perform our heavy duty tasks.
//I have used a simple datareader object to traverse all the rows in the table.
//The table has around 19K rows.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  try
  {
    int i = 0;
    cmd = new SqlCommand("SELECT * FROM Person.Contact", con);
    con.Open();
    dr = cmd.ExecuteReader();
    while(dr.Read())
    {
        i = i + 1;
        //report to the backgroungworker progreechanged event of the background worker class
        backgroundWorker1.ReportProgress(i);
        Thread.Sleep(1);
        //Called and check if the cancellation of the operation is pending. If returned true
        //DoWorkEventArgs object cancels the operation.
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            return;
        }
    }
   }
   catch (Exception x)
   {
    MessageBox.Show("An error occured while performing operation" + x);
   }
   finally
   {
    con.Close();
   }
}
The RunWorkerCompleted Method:
You may want to have the result of your task in your UI. Again for this purpose you have a property called Result which you can set it in your DoWorkEventArgs. And it will be accessible in your RunWorkerCompletedEventArgs of RunWorkerCompleted event.
private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("Operation Cancelled");
        btn_start.Enabled = true;
    }
    else
    {
        MessageBox.Show("Operation Completed");
        btn_start.Enabled = true;
    }
}
The ProgressChanged Method:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //Report porogress bar change
    progress.Value = e.ProgressPercentage;
}
Ending up with the cancel button:
//To cancel async operation
private void btn_cancel_Click(object sender, EventArgs e)
{
     //To cancel the asynchronous operation
     backgroundWorker1.CancelAsync();
     progress.Value = 0;
     btn_start.Enabled = true;
}
So when your application is traversing the records and suddenly you think that you should quit the job and work on other part of the application, just hit the cancel button and the large operation will get cancelled without any freezing and hanging of your application.

Reference Links
4) 

24 February 2012

C#: Check if Form is already running

While implementing WinForms programming you might come across a situation where you do not want to open a form multiple times on an event.  A common practice in the event handler function is:
From1 firstForm = new From1();
firstForm.Show(); 
This will open your form, fine! But what if the event happens again and the previously opened firstForm has not been closed yet? A new firstForm will be opened and this will go on.  To check if a form is already running you’ll have to look for it in the Application.OpenForms collection. When a form is opened it is added to that collection. Here’s a boolean method that checks whether a form is open or not. This code snippet shows you how to check if is your MDI container has a specific MDI child open or not. The sample below looks though each of the mdi children in the container for a instance of the form you want to open. If an instance is found, the form is brought to the front. If an instance of the form is not found, the code opens a new instance of the form.

Boolean Method
To check whether the form is already opened or not      
      private bool CheckForm(Form form)
        {
            form = Application.OpenForms[form.Text];
            if (form != null)
                return true;
            else
                return false;
        }
Example use:
                       Form2 formSecond = new Form2();
                        if (!CheckForm(formSecond ))
                        {
                            formSecond .Show();
                        }
                        else
                        {
                            formSecond .WindowState = FormWindowState.Normal;
                            formSecond .BringToFront();
                            formSecond .Activate();
                        }

10 February 2012

Crystal Reports Set Row Height

To increase the row height in Crystal Report designer keep a TextObject in details section and drag your desired field from FieldExplorer onto it. Then, Right-Click TextObject in Details Section then select Format Object form the context menu.

When click on Format Object then it will show Format Editor Window as shown bellow. Enter the values in Minimum number of lines you wand check the Can Grow option. and then click on Ok button.