3

Dynamic Buttons Controls Event Handling WinForms Windows Forms

Dynamic Buttons Controls Event Handling In Windows Forms Or Winforms Applications In .Net 2.0,3,5. C# And VB.NET.

Dynamic Buttons in winforms
many times we need to create controls at runtime or through code behind depending on the real time scenario.

In this post i am going to explain how to add dynamic buttons at runtime and handle the Button Click event in winforms or windows forms applications.

I am creating 3 buttons on Form_Load event and placing them on the form.



Write this code in Load event of windows form.


C# Code

private void Form1_Load(object sender, EventArgs e)
        {
            int x = 50, y = 50;
            for (int i = 1; i <= 3; i++)
            {
                Button btnDynamic = new Button();
                btnDynamic.Location = new System.Drawing.Point(x, y);
                btnDynamic.Name = " Dynamic Button " + i;
                btnDynamic.Size = new System.Drawing.Size(100, 50);
                btnDynamic.Text = btnDynamic.Name;
                Controls.Add(btnDynamic);
                x += 100;
                btnDynamic.Click += new EventHandler(this.DynamicButtonClick);
            }
            
        }

Here x and y are horizontal and vertical cordinates where dynamically created buttons will be placed.

x is incremented by 100 each time so that buttons don't get placed overlapped.

when button is created, eventhandler for Click Event of button is associated with it in last line of above mentioned method.

Now write below mentioned method signature in the code behind

private void DynamicButtonClick(object sender, EventArgs e)
   {

   }

Method name must be exactly the same u mentioned in eventhandling code, as It's case sensitive. Write this code inside this method

private void DynamicButtonClick(object sender, EventArgs e)
        {
            Button btnDynamic = (Button)sender;
            btnDynamic.Text = "You Clicked" + btnDynamic.Name;
                      
        }

VB.NET Code

Private Sub Form1_Load(sender As Object, e As EventArgs)
 Dim x As Integer = 50, y As Integer = 50
 For i As Integer = 1 To 3
  Dim btnDynamic As New Button()
  btnDynamic.Location = New System.Drawing.Point(x, y)
  btnDynamic.Name = " Dynamic Button " & i
  btnDynamic.Size = New System.Drawing.Size(100, 50)
  btnDynamic.Text = btnDynamic.Name
  Controls.Add(btnDynamic)
  x += 100
  btnDynamic.Click += New EventHandler(AddressOf Me.DynamicButtonClick)
 Next

End Sub

Private Sub DynamicButtonClick(sender As Object, e As EventArgs)
 Dim btnDynamic As Button = DirectCast(sender, Button)
 btnDynamic.Text = "You Clicked" + btnDynamic.Name

End Sub


Build the application and run.

0

Context.User.Identity.Name Is Empty Null Blank

Context.User.Identity.Name Is Empty Null Or Blank In Asp.Net. If you have set the forms authentication and trying to display logged in user name in your asp.net web application by getting the user name using user.identity.name and this is blank or empty as displayed in image below.

Context.User.Identity.Name is Empty

Then u might have missed few configuration settings.

If yor are getting user identity name null or emplty when u try to get it to display user name in welcome message (for example) then probably you have allowed anonymous access to your site hence user.identity.name is null.

To avoid this try to write the code as mentioned below

First of all set authentication mode to forms authentication in web.config file




Now deny anonymous access to your site by adding below mentioned code in authorization section of web.config.






the ? represents anonymous user

Now write this code in Page_load to check the value of Identity name.

protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                lblName.Text = HttpContext.Current.User.Identity.Name.ToUpper().ToString();

            }
                      
        
        }
        
    }

Context.User.Identity.Name is Blank

Now identity name is not blank as shown in picture.

You may also read more about Forms Authentication And FormsAuthenticationTicket.

5

Pass Crystal Report Parameters Programmatically Asp.Net

Pass Crystal Report Parameters Programmatically In Asp.Net 2.0,3.5,4.0 Using C# And VB.NET. In this post i am explaining how to pass parameters to crystal reports programmatically in code behind of asp.net web page.

Pass Crystal Report Parameters Programmatically In Asp.Net

For this example i am using northwind database and products table.

I have put one text box on the page and report will display details of product based on product id entered by user.

Read how to create Crystal Reports In Asp.Net , Or Windows Forms.


Open crystal report in design view, right click on it and select Field Explorer

Now select Parameter Fields and select new to add new parameter to report.

Name it as ProductID and remember it.

Now click on Special Fields in Field Explorer and select Record Selection Formula.

Select is equal to and {?ProductID} from the dropdowns and click on OK.

Click on smart tag of reportviewer control and uncheck Database logon prompting and parameter prompting as we will provide these info in code behind.


HTML markup of aspx page

<form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td>
                Enter Product ID :
            </td>
            <td>
                <asp:TextBox ID="txtProductID" runat="server">
                </asp:TextBox>
                </td>
            <td>
                <asp:Button ID="btnReport" runat="server" 
                            Text="Show Report" 
                            onclick="btnReport_Click" 
                            Width="108px" />
                </td>
        </tr>
    </table>
    <br />
    <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" 
        AutoDataBind="True" EnableDatabaseLogonPrompt="False" 
        EnableParameterPrompt="False" Height="1039px" 
        ReportSourceID="CrystalReportSource1" 
        ReuseParameterValuesOnRefresh="True" 
        Width="901px" DisplayGroupTree="False" />
    <CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
        <Report FileName="CrystalReport.rpt">
        </Report>
    </CR:CrystalReportSource>
    </form>


Now go to code behind of the page and add below mentioned namespace for crystal reports.

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;

Write this code in Page_Load event of the page

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack) CrystalReportViewer1.Visible = true;
        else
            CrystalReportViewer1.Visible = false;
    }

Generate click event for button to shaow report and write this code.

protected void btnReport_Click(object sender, EventArgs e)
    {   //Create report document
        ReportDocument crystalReport = new ReportDocument();
        
        //Load crystal report made in design view
        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));

        //Set DataBase Login Info
        crystalReport.SetDatabaseLogon
            ("amitjain", "password", @"AMITJAIN\SQL", "Northwind");

        //Provide parameter values
        crystalReport.SetParameterValue("ProductID", txtProductID.Text);
        CrystalReportViewer1.ReportSource = crystalReport;
    }

Build the solution and run.


have fun.

3

Asp.Net QueryString Example

QueryString Example In Asp.Net 2.0,3.5,4.0 With Multiple Variable Values Using C# And VB.NET. Several time in ASP.NET applications we need to transfer data or information provided by user from one aspx page to another.

We can achieve this using several methods like Cookies,Session or Crosspage posting

In this post i am explaining how to use querystrings.

Example url with querystring can be something similar like this

http://yourdomainname.com/defauld.aspx?variable1=value1&variable2=value2

Suppose we have a textbox txtData and we want it's value on other page
than in code behind we would write in click event of btnGo

private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text);
}

Or

private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?city=" +
txtData.Text + "&country=" + txtcountry.Text);
}


Now to retrieve these values on other page we need to use request.querystring, we can either retrieve them by variable name or by index

private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString["city"];
txtCountry.Text = Request.QueryString["country"];
}

Or we can also use

private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString[0];
txtCountry.Text = Request.QueryString[1];
}



QueryString can't be used for sending long data because it has a max lenght limit

Data being transferred is visible in url of browser

To use spaces and & in query string we need to replace space by %20 and & by %26


private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text.Replace(" ","%20");
}

Or we can use Server.UrlEncode method

private void btno_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.Aspx?" +
"Name=" + Server.UrlEncode(txtData.Text));
}


2

Select Find Nth Highest Salary Record In Sql Server

Select Find Get Second Third Nth Highest Salary Record Row In Ms Sql Server. This is most frequentky asked question how to select or get nth highest record or second third row/record from any column of sql table.

Select Find Nth Highest Record In Ms Sql Server
for example select get or fetch 2nd (second highest) or nth highest salary of employee or 10th highest record from the table.

There are various ways to achieve this result, i've mentioned few here.

I have created Employee table with following schema.










1st method

To select 2nd highest salary or record we can use following query.

SELECT TOP 1 [Salary]
FROM 
(
SELECT  DISTINCT TOP 2 [Salary]
FROM [dbo].[Employee]
ORDER BY [Salary] DESC
) temp
ORDER BY [Salary] 


2nd method

To select 3rd highest salary or record we can use following query.
SELECT TOP 1 [Salary]
FROM ( SELECT  TOP 3 [Salary]
  FROM [dbo].[Employee] e1 GROUP BY e1.Salary
  ORDER BY [e1].[Salary] DESC) e2
  ORDER BY [Salary]


These queries holds good untill we are selecting only salary column and fails when we want to select all the columns or few more columns with salary as salary can be same for more then one employees or records.

For example if we change the first query to select 2nd highest salary with all the columns of table, output would be undesirable as shown below.
SELECT TOP 1 [Salary],[EmployeeName]
FROM 
(
SELECT  DISTINCT TOP 2 [Salary], [EmployeeName]
FROM [dbo].[Employee]
ORDER BY [Salary] DESC
) temp
ORDER BY [Salary]


To select all columns we can use queries mentioned below.

This query will give 4th highest salary record but will show only 1 highest record if even if there are multiple duplicate salary records.

SELECT TOP 1 * FROM [dbo].[Employee]
WHERE [Salary] NOT IN  
( 
  SELECT DISTINCT TOP 3 [Salary] FROM [dbo].[Employee]
  ORDER BY [Salary] DESC
)
ORDER BY [Salary] DESC


These 2 queries will select 4th highest salary with duplicate records.
SELECT * FROM [dbo].[Employee]
WHERE [Salary] = 
( 
  SELECT MAX([Salary]) FROM [dbo].[Employee] 
  WHERE [Salary] NOT IN
    ( 
      SELECT DISTINCT TOP (4-1) [Salary] FROM [dbo].[Employee] e1
      ORDER BY [Salary] DESC 
    )
)

SELECT *
FROM Employee E1
WHERE (4-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE E2.Salary > E1.Salary)



We can also use sql ranking function to get desired result as follows.

SELECT * FROM 
(
  SELECT DENSE_RANK() OVER(ORDER BY [Salary] DESC)AS RowId, * 
  FROM [dbo].[Employee] 
) AS e1
  WHERE e1.RowId = 4  



1

Forms Authentication In Asp.Net

Forms Authentication In Asp.Net 20.,3.5,4.0 With Folder Level Access And Managing Roles

Forms Authentication in asp.net

In examples below i'm explaining how to use forms authentication in Asp.Net and forms authentication tickets in Asp.net.












Forms Authentication In Asp.Net 2.0 and 3.5


Forms Authentication in ASP.NET is technique to decide how users can access your web application.

Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles.

we can manage the access through web.config file or folder level access and through multiple web.config files using forms authentication.

Read More


Forms Authentication Ticket In Asp.Net 2.0 And 3.5


In this article i am going to describe how to implement Forms authentication tickets and manage user roles based access in ASP.NET using C# and multiple web.config files

Read More


Bypass Forms Authentication Or Skip Authorization


Some readers ask me how to skip or bypass forms authentication or Authorization for selected pages in asp.net or a scenario where only few pages on site needs user to log in rest can be accessed without login.

Read More


Detecting Session Timeout and Redirect to Login Page in ASP.NET


In this example i'll show how to detect the session timeout which occurs when user is idle for the time specified as Session imeout,using forms authentication,C# asp.NET and if it is than redirect the user to login page to login again, for this i've set time out value in web.config file to 1 minute

Read More



Have fun

7

Maintain Scroll Position On After Postback in Asp.Net 2.0 3.5

In this example i'm explaining different methods of Maintaining Scroll Position On/After Postback In Asp.Net 2.0,3.5,4.0 Web pages or Applications.


Maintain scroll position after postback
Method 1 .

Write below mention directive in page directive section of html source of aspx page to maintain scroll position of only one page or selected pages rather then whole web application.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"  
         MaintainScrollPositionOnPostback="true"  Inherits="_Default" %>



Method 2.

To maintain scroll position programmatically use code mentione below.
System.Web.UI.Page.MaintainScrollPositionOnPostBack = true;


Method3.

To maintain scroll position application wide or for all pages of web application we can write below mentioned code in pages section of web.config file so that we don't need to add page directive in each and every page.

<pages maintainScrollPositionOnPostBack="true">

Hope this helps.

5

Create Setup And Deployment Project in Visual Studio 2008/2010

Create Setup And Deployment Project In Visual Studio 2008/2010 For Asp.Net Web And Windows Applications

Create setup Project In Visual Studio

In this example i am going to explain how to create setup and deployment project for winforms windows application using visual studio 2005/2008/2010.

Similar approach can be applied for creating setup project for web application as well.


First of all create any sample windows/web application.

Create setup project


Right click on solution explorer root and select Add > New project 



In add new project dialog box select setup and deployment from other project types and then select Setup Project.


In the setup project file system editor window, right click on Application folder > Add > Project Output 


Now select primary output from next dialog box and click on OK.



Right click on User's desktop and create shortcut to primary output in application folder.


Similarly add shortcut in user's program menu.


Build the project by right clicking on setup project name and run the setup.


Hope this helps 




Download the sample code attached 




Find More Articles