Archive

Posts Tagged ‘asp.net’

ASP.NET: Create user Control

May 24, 2011 Leave a comment

In this article, we will be building a simple User Control to demonstrate how a ASP.NET User Control can be added into a ASPX page.

 

Assuming that you created an Empty Web Application from Visual Studio, you now create a new User Control by right-click on your web application > Add > New Item and name it MyUserControl.ascx. Then click Add.

aspnet_userControl_create

Now, you have created your User Control. Now, lets put in some text so that we can see it in the web page later.

aspnet_userControl_ascx

Next, we will add this User Control into our ASPX web page. First, you have to register your User Control on the top of your page, under the @Page declaration. You should add the @Register declaration like below.

 

<%@ Register src="UserControl/MyUserControl.ascx" tagname="MyUserControl" tagprefix="uc1" %>

 

The “src” property should be pointing to where your ASCX file is located. Then you can name the “tagname” and “tagprefix” property. By default, the “tagname” will be your User Control file name, and the “tagprefix” will be “uc1” if you are adding the first User Control in the page.

 

Next, you add the control into your page like how you add a Button  or Label into your webpage. Add the following code into the Body.

 

<uc1:MyUserControl ID="MyUserControl1" runat="server" />

 

Your ASPX page code should look like the following.

aspnet_userControl_aspx

Now, save and run your code. You will see that your User Control is loaded into the web page. You have just successfully added a custom User Control into your web page.

Categories: ASP.NET Tags: , ,

Databinding GridView programatically

December 7, 2010 Leave a comment

In my previous post, I’ve showed how to bind data to GridView using SqlDataSource. Here, I’ll show how to bind data to GridView using code behind.

 

Assumptions:
I assume you already have a ready database that have a Customers table. Also you have pre-define a connection string in your web.config file.

 

Code for ASPX page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebDemo_CS.Web.Data.GridView.DatabindProgramatically.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Databind GridView Programatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            Databind GridView Programatically</h1>
        <asp:Label runat="server" ID="Label1" ForeColor="Red" />
        <br />
        <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="true">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code for C#:

protected void Page_Load(object sender, EventArgs e)
        {
            // This example uses Microsoft SQL Server and connects
            // to the Northwind sample database. The data source needs
            // to be bound to the GridView control only when the
            // page is first loaded. Thereafter, the values are
            // stored in view state.                     
            if (!IsPostBack)
            {
                // Declare the query string.
                String queryString = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";

                // Run the query and bind the resulting DataSet
                // to the GridView control.
                System.Data.DataSet ds = GetData(queryString);
                if (ds.Tables.Count > 0)
                {
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
                else
                {
                    Label1.Text = "Unable to connect to the database.";
                }
            }
        }

        System.Data.DataSet GetData(String queryString)
        {
            // Retrieve the connection string stored in the Web.config file.
            String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

            System.Data.DataSet ds = new System.Data.DataSet();

            try
            {
                // Connect to the database and run the query.
                System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);
                System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(queryString, connection);

                // Fill the DataSet.
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                // The connection failed. Display an error message.
                Label1.Text = "Unable to connect to the database.";
            }

            return ds;
        }

Code for VB.NET:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ‘ This example uses Microsoft SQL Server and connects
        ‘ to the Northwind sample database. The data source needs
        ‘ to be bound to the GridView control only when the
        ‘ page is first loaded. Thereafter, the values are
        ‘ stored in view state.                     
        If Not IsPostBack Then

            ‘ Declare the query string.
            Dim queryString As String = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"

            ‘ Run the query and bind the resulting DataSet
            ‘ to the GridView control.
            Dim ds As DataSet = GetData(queryString)
            If (ds.Tables.Count > 0) Then
                GridView1.DataSource = ds
                GridView1.DataBind()
            Else
                Label1.Text = "Unable to connect to the database."
            End If

        End If
    End Sub

    Protected Function GetData(ByVal queryString As String) As DataSet
        ‘ Retrieve the connection string stored in the Web.config file.
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
        Dim ds As New DataSet()

        Try
            ‘ Connect to the database and run the query.
            Dim connection As New System.Data.SqlClient.SqlConnection(connectionString)
            Dim adapter As New System.Data.SqlClient.SqlDataAdapter(queryString, connection)

            ‘ Fill the DataSet.
            Adapter.Fill(ds)

        Catch ex As Exception
            ‘ The connection failed. Display an error message.
            Label1.Text = "Unable to connect to the database."
        End Try

        Return ds
    End Function

Conclusion:

Data bind data into GridView from code behind provides more flexibility as you can control the data to be selected from the database dynamically.

Categories: ASP.NET Tags: , ,

Databinding GridView using SqlDataSource

December 6, 2010 1 comment

The GridView control in ASP.NET is a control that displays the data that you selected from the database in a form of a table where each row represents a record in the database. GridView also allows you to select, update, delete, and sort the data.

In addition, GridView also allows you to customize how the data is to be represented to the user when the data is binded from the database.

Here, I’ll show you how to bind data into the GridView control using SqlDataSource control as the data source.

 

Assumptions:
I assume you already have a ready database that have a Customers table. Also you have pre-define a connection string in your web.config file.

 

Code for ASPX Page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebDemo_VB.Web._GridView_SqlDataSource_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" DataKeyNames="CustomerID"
            DataSourceID="SqlDataSource1" EnableModelValidation="True">
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="StaffID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
                <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
            SelectCommand="[CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

The code above shows a simple method on how to data bind the GridView to display information from the Customers table in the database. This is the most simple way of data binding a GridView control.

Note: For advanced data binding and customization method, please wait/see the later post.

Getting ConnectionStrings value from code behind

December 5, 2010 Leave a comment

When you do wants to get some data from a database to show it on your ASP.NET web application, you will need to use a connection string to connect to the database. This string is very important because, at most conditions, you will be using this string again and again across the entire application. Therefore, you can utilize the ConnectionStrings tag in the web.config file to store your predefined connection strings.

Well, some programmers will say “Why do I need to store it in the web.config file? I can just code it in my code behind codes and it will still work the same.”. Yes, it will still work the same. But that is only suitable for a mini web application that does not require much connection to the database. However, if it’s a big web application and the connection string values have to be changed, the programmers will spend a long time just to find and replace the existing connection string to the new string.

Therefore, it’s advised to always store a connection string in the web.config file and get its value from here. Below, I will show you how to get the connection string values from the ConnectionStrings tag in the web.config file.

 

Code in web.config:

<connectionStrings>
        <add name="MyConnectionString" connectionString="Your connection string here" providerName="System.Data.SqlClient" />
</connectionStrings>

Code for C#:

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

Code for VB.NET:

System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString

From the sample above, I’ve named my connection string to “MyConnectionString”. For the connectionString values which I’ve written as “Your connection string here”, you will have to replace it with a proper connection string. You can find more about connection string from http://connectionstrings.com/. As for the providerName, you have to put the namespace of the data connection class. In this case above, “System.Data.SqlClient” will be connecting to Microsoft SQL Server.

Get AppSettings value from code behind

December 4, 2010 1 comment

When you are developing an ASP.NET web application, you sometimes may need to reuse a term or name over and over again across the application. If the term is used in some places only, there might not be a problem to change it when you need to change the term.

However, if the application that you are developing is a big application, it will be very tedious if you need to change the term value after lots of pages has been coded. So how do you solve this?

The solution is to use AppSettings which can be located in the web.config. Values that has been added into the AppSettings tag in the web.config file can be accessed across the entire application. So, any changes made to the value of the AppSettings, it will be applied across the entire application without having to change the values page by page.

Below, I’ll be showing you how to access the AppSettings values you have added into the web.config file from the code behind file. You can also access this values from class file in your application.

 

Note: I have added a Label with the ID of “Label1” in the Default.aspx file.

 

Code in web.config:

<appSettings>
        <add key="MyAppSettings" value="Some value" />
</appSettings>

Code for C#:

Label1.Text = System.Configuration.ConfigurationManager.AppSettings["MyAppSettings"].ToString();

Code for VB.NET:

Label1.Text = System.Configuration.ConfigurationManager.AppSettings("MyAppSettings").ToString()

 

The sample code above shows you how to get the value of the key “MyAppSettings” from the collection of pre defined application settings from the AppSettings tag in the web.config file. Then it displays the value out to the Label with ID “Label1”.

 

Note: Make sure that your web application has reference to System.Configuration. Otherwise, you will get errors when you compile your web application.

Get AppSettings value in ASPX page

December 4, 2010 1 comment

In my previous post, I’ve shown how to get AppSettings value from the code behind file. Here, I’ll show you how to get AppSettings value directly from the .ASPX page.

The sample below displays the value for “MyAppSettings” key stored in web.config file as the text for a label named “Label1”.

 

Code for ASPX page:

<asp:Label Text='<%$ AppSettings:MyAppSettings %>’ runat="server" ID="Label1" />

Code in web.config:

<appSettings>
        <add key="MyAppSettings" value="Some value" />
</appSettings>

Categories: ASP.NET Tags: , ,

How to: Encrypt/Decrypt web.config

October 17, 2010 Leave a comment

When you are developing a ASP.NET Web Application, you know that the web.config file is a very important file to your web application. This is because, it contains all/part of your application settings, such as connection strings. So, when you have completed developing your web application and wants to deploy it to the server, you might want to encrypt the web.config file first. This is to make sure that nobody knows what is the content in that web.config file if they manage to get a copy of it. Well of course IIS will not allow any request to view/download the web.config file.

You can encrypt/decrypt the web.config file at any time. Take note that you can ONLY decrypt an encrypted web.config file on the machine that encrypted the web.config. Here is several ways of how you can encrypt your web.config files:

Encrypt

  1. Open up a Command Prompt.
    For Windows XP: press Win+R, then type in “cmd” and hit Enter.
    For Windows Vista/Windows 7: Press start and type “cmd” in the search bar. Click on the “Cmd” program.
  2. Navigate to the the directory “C:\Windows\Microsoft.NET\Framework\v2.0.50727\
  3. Then, type in the following:
    aspnet_regiis -pe “connectionStrings” -app “/SampleApplication” -prov “RsaProtectedConfigurationProvider”

NOTE:

This sample above is to encrypt the “connectionStrings” section for the application “SampleApplication” using the provider “RsaProtectedConfigurationProvider”.

 

Decrypt

  1. Open up a Command Prompt.
    For Windows XP: press Ctrl+R, then type in “cmd” and hit Enter.
    For Windows Vista/Windows 7: Press start and type “cmd” in the search bar. Click on the “Cmd” program.
  2. Navigate to the the directory “C:\Windows\Microsoft.NET\Framework\v2.0.50727\
  3. Then, type in the following:
    aspnet_regiis –pd “connectionStrings” -app “/SampleApplication”
Categories: ASP.NET Tags: , , ,