ASP.NET – How to work with GridView

Today we are going to see how to work with Grid View Control.

Here is an example how are we going to get a repeater after we finished coding.

Here I am using AdventureWorks in SQL SERVER which can be downloaded from codeplex.

The table I am using is DimCustomer and fields are :

1)FirstName

2)MiddleName

3)LastName

4)BirthDate

5)CustomerKey

Step 1 :  Add the control in the <body> tag in page in .aspx side let it be grdView.aspx

</pre>
<form id="frmExmGrdView" runat="server">
    <asp:GridView ID="grd" runat="server" CssClass="gdview" HeaderStyle-CssClass="hd" AutoGenerateColumns="false" BorderStyle="None">
    <Columns>
    <asp:BoundField DataField="FirstName" HeaderText="Login" ItemStyle-Width="40" ItemStyle-HorizontalAlign="Left" ></asp:BoundField>
    <asp:BoundField DataField="MiddleName" HeaderText="Initial" ItemStyle-Width="20" ItemStyle-HorizontalAlign="Left" ></asp:BoundField>
    <asp:BoundField DataField="LastName" HeaderText="Name" ItemStyle-Width="60" ItemStyle-HorizontalAlign="Left" ></asp:BoundField>
    <asp:BoundField DataField="BirthDate" HeaderText="DateAdded" ItemStyle-Width="40" ItemStyle-HorizontalAlign="Left" HtmlEncode="false" DataFormatString={0:d}></asp:BoundField>
    </Columns>
    </asp:GridView>
    </form>
<pre>

NOTE: Dont forget to make the form tag as runat = “server “

otherwise an error will occur because you are trying to insert the data from .cs

side but u can only access it when u make runat = “server “

STEP 2:  Now insert the data from the code behind (.cs side) in Page_Load event

 

protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Server=localhost;UID=sa;PWD=dilip;Database=AdventureWorksDW");
        string sSQL = "Select top 5 * from dbo.DimCustomer";
        SqlCommand cmd = new SqlCommand(sSQL, con);
        con.Open();
        SqlDataReader dtrClient = cmd.ExecuteReader();
        grd.DataSource = dtrClient;
        grd.DataBind();
        con.Close();
    }

The last 2 lines binding the data to the repeater and starting remaining lines is to establish connection to database.

the output will come as shown above .

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

ASP.NET How to work with Repeater

Today we are going to see how to work with Repeater Control.

Here is an example how are we going to get a repeater after we finished coding.

Here I am using AdventureWorksDW2008R2 in SQL SERVER which can be downloaded from http://www.codeplex.com.

The table I am using is DimCustomer and fields are :

1)FirstName

2)MiddleName

3)LastName

4)BirthDate

5)CustomerKey

Step 1 :  Upload the control in the page in .aspx side let it be default.aspx

<form id=”frmExample” runat=”server”>

<asp:Repeater ID=”rptList” runat=”server” OnItemDataBound=”rptList_ItemDataBound”>

<HeaderTemplate>

<table border=”1″ cellpadding=”0″ cellspacing=”0″>

12px; color:White;”>

<th>

<asp:Label ID=”Label14″ Text=”Login” runat=”server”></asp:Label>

</th>

<th>

<asp:Label ID=”Label1″ Text=”First Name” runat=”server”></asp:Label>

</th>

<th>

<asp:Label ID=”Label2″ Text=”Last Name” runat=”server”></asp:Label>

</th>

<th>

<asp:Label ID=”Label3″ Text=”Date Added” runat=”server”></asp:Label>

</th>

<th>

<asp:Label ID=”Label6″ Text=”Delete” runat=”server”></asp:Label>

</th>

</tr>

</HeaderTemplate>

<ItemTemplate>

<tr>

<td>

<asp:LinkButton ID=”lbnLogin” Text='<%# Eval(“FirstName”) %>’ runat=”server”</asp:

OnClick=”lnkClient_Click” CommandArgument='<%# Eval(“CustomerKey“).ToString() %>’>

LinkButton>

</td>

<td>

<asp:LinkButton ID=”lbnFirstName” Text='<%# Eval(“MiddleName”).ToString() %>'</asp:

runat=”server”

OnClick=”lnkClient_Click” CommandArgument='<%# Eval(“CustomerKey“).ToString() %>’>

LinkButton>

</td>

<td>

<asp:LinkButton ID=”LinkButton2″ Text='<%# Eval(“LastName”).ToString() %>'</asp:

runat=”server”

OnClick=”lnkClient_Click” CommandArgument='<%# Eval(“CustomerKey“).ToString() %>’>

</asp:LinkButton>

</td>

<td>

<asp:LinkButton ID=”LinkButton1″ Text='<%# string.Format(“{0:d}”, Eval(“BirthDate”)) %>’ runat=”server”

OnClick=”lnkClient_Click” CommandArgument='<%# Eval(“CustomerKey“).ToString() %>’>

</asp:LinkButton>

</td>

<td>

<asp:LinkButton ID=”lbnDelete” Text=”delete” runat=”server”

OnClick=”lbnDelete_Click” CommandArgument='<%# Eval(“CustomerKey“).ToString() %>’>

</asp:LinkButton>

</td>

</tr>

</ItemTemplate>

<FooterTemplate>

</table>

</FooterTemplate>

</asp:Repeater>

</form>

NOTE: Dont forget to make the form tag as runat = “server “

otherwise an error will occur because you are trying to insert the data from .cs

side but u can only access it when u make runat = “server “

STEP 2:  Now insert the data from the code behing

int Page_Load event

SqlConnection con = new SqlConnection(“Server=localhost;UID=xx;PWD=xx;

Database=AdventureWorksDW2008R2″);

string sSQL = “Select top 5 * from dbo.DimCustomer”;

SqlCommand cmd = new SqlCommand(sSQL, con);

con.Open();

SqlDataReader dtrClient = cmd.ExecuteReader();

rptList.DataSource = dtrClient;

rptList.DataBind();

con.Close();

/*along with it*/ write these dummy function later you can implement them as you like .

protected void lnkClient_Click(object sender, EventArgs e)

{ }

protected void lbnDelete_Click(object sender, EventArgs e)

{ }

protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)

{ }

The last 2 lines binding the data to the repeater and starting remaining lines is to establish connection to database.

the output will come as shown above .

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DOT NET – How to make a button as default button and set Focus on a particular text box

In the initial days when i was new to development side and in some site i used to login straight away when i enter username and password and hit Enter key on my keyboard.

I used to think how is this happening but never had any answer but now i am going to show how thats possible.

In this post I will be talking about how  to make any button Default button and set Focus on a particular text box in any page thats displayed.

Ex: Make a test site and go to default.aspx

Step 1:

in <body> tag write the following code

<body>

<form id=”frmExample” runat=”server” defaultbutton=”btnLogin” defaultfocus=”txtUserName”>

<table><tr><td width=”50%”>

Welcome to the Example Web site from dilip

</td>

<td width=”50%”>

<table>

<tr><td><asp:TextBox ID=”txtUserName” runat=”server” Text=”UserName” /></td><td><asp:TextBox ID=”txtPassword” runat=”server” Text=”Password”/></td></tr>

<tr><td><asp:Button ID=”btnLogin” runat=”server” Text=”Login” onclick=”btnLogin_Click”/></td><td><asp:Button ID=”btnSignIn” runat=”server” Text=”Signup”/></td></tr>

</table>

</td>

</tr>

</table>

</form>

</body>

Note: Here the beauty is that i have login and singnup button and i made defaultbutton as login button, and defaultfocus on username text box so whenever this page is viewed from any web browser focus will be on username text box and default button will be login button so when u hit enter it will invoke login button so simple.

 Step 2: see  carefully i have a function onclick=”btnLogin_Click” now press F7 key and go to .cs side of the same page or right click on the mouse and select view code .

and write the following code in .cs side

protected void btnLogin_Click(object sender, EventArgs e)

{

Response.Write(“Default Button was clicked and u are now logged In”);

Response.End();

}

Note: Here another concept when ever you enter key this method will be invoked and at the same time there wont be any other you can see that means response is closed just to make you feel that you really logged in but actually u are in same page.

the output is some this like this :

First Time when visited:

you can see username text box is in focus.

Then when enter key is pressed:

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DOT NET 4.0 – Features of DOT NET

Interoperability

Because interaction between new and older applications is commonly required, the .NET Framework provides means to access functionality that is implemented in programs that execute outside the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and System.EnterpriseServices of the framework.

 

Common Runtime Engine

Programming languages on the .NET Framework compile into an intermediate language known as the Common Intermediate Language (CIL). In Microsoft’s implementation this intermediate language is not interpreted but rather compiled in a manner known as just-in-time compilation (JIT) into native code.

 

Language Independence

The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all possible datatypes and programming constructs supported by the CLR and how they may or may not interact with each other. Because of this feature, the .NET Framework supports the exchange of instances of types between programs written in any of the .NET languages.

 

Base Class Library

The Base Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions.

 

Simplified Deployment

Installation of computer software must be carefully managed to ensure that it does not interfere with previously installed software, and that it conforms to increasingly stringent security requirements. The .NET framework includes design features and tools that help address these requirements.

 

Portability

The design of the .NET Framework allows it to theoretically be platform agnostic, and thus cross-platform compatible. That is, a program written to use the framework should run without change on any type of system for which the framework is implemented. Microsoft’s commercial implementations of the framework cover Windows. In addition, Microsoft submits the specifications for the Common Language Infrastructure (which includes the core class libraries, Common Type System, and the Common Intermediate Language), the C# language to both ECMA and the ISO, making them available as open standards. This makes it possible for third parties to create compatible implementations of the framework and its languages on other platforms.

 

Memory management

It is the act of managing computer memory. In its simpler forms, this involves providing ways to allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed.

The management of main memory is critical to the computer system. In this process it uses the Garbage Collection which is the automated allocation, and deallocation of computer memory resources for a program.

This is generally implemented at the programming language level and is in opposition to manual memory management, the explicit allocation and deallocation of computer memory resources.

In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application. Garbage collection was invented by John McCarthy around 1959 to solve the problems of manual memory management.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

Dot Net – How to upload excel sheet into databse using Dataset in ASP.NET

I thought of writing this blog post because there can a number of occasion where in you might need to upload something from word file or excel sheet or it can be any kind of  file need to be inserted into the database what we can do many things.

But probably what I feel good and follow most of the time is doing this way so that we can preserve the statements for future reference what we have actually used and where it is going to exactly affect.

Step 1: Create  a website and then add default page on to it.

Step 2: Write the following code in Page_Load(object sender, EventArgs e) function

DataSet ds = new DataSet();

OleDbConnection myCon = new OleDbConnection(@”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=folderpath\sheet.xls;Extended Properties=Excel 8.0;”);

OleDbCommand myComm = new OleDbCommand(“select * from [sheet1$] where State<>””, myCon);

OleDbDataAdapter da = new OleDbDataAdapter(myComm);

da.Fill(ds);

for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )

{

Response.Write(“insert into dbo.Temp2 values(‘” + ds.Tables[0].Rows[i][0].ToString() + “‘,'” + ds.Tables[0].Rows[i][1].ToString() + “‘,'” + ds.Tables[0].Rows[i][2].ToString() + “‘,'” + ds.Tables[0].Rows[i][3].ToString() + “‘)<br />”);

}

myCon.Close();

Step 3: Create a table in SQL Server names Temp2 where in u want insert the excel sheet into.

NOTE: The table name can be any name  you like its just an example never take it as standard, its for learing.

create table Temp2(Id varchar(10),country varchar(100),natAnimal varchar(50),lang varchar(50))

Step 4: Create or if u have  excel sheet just make sure that that contains header for each column it will be easy to understand

EX:

State Country Animal Language
1 Australia Kangroo English
2 India Peacock Hindi
3 USA American Biston English

This is a sample excel sheet name it as sheet and inside as Sheet1 it will be applied by default so just hit the save button.

So all set!!!

now save the excel sheet in the folder of your website and run the web site the expected Output will be something like this will appear in your broswer

insert into dbo.Temp2 values(‘1′,’Australia’,’Kangroo’,’English’)

insert into dbo.Temp2 values(‘2′,’India’,’Peacock ‘,’Hindi’)

insert into dbo.Temp2 values(‘3′,’USA’,’American Biston’,’English’)

then copy it and paste in ssms (SQL server Query Editor and hit F5 to execute) Finally records are inserted into the database.

There can be many more ways I am sure but this is also handy when you have production and development section seperate.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DotNet FrameWork – What actually happens when you add something to an arraylistcollection – How Boxing and unboxing occures in memory – Why only boxed types can be unboxed – Day 30 of 30

What actually happens when you add  something to an arraylistcollection ?

Following things will happen :

Arraylist is a dynamic array class in c# in System.Collections namespace derived from interfaces – ICollection , IList , ICloneable , IConvertible  . It terms of in memory structure following is the implementation .

a. Check up the total space if there’s any free space on the declared list .

b. If yes add the new item and increase count by 1 .

c. If No Copy the whole thing to a temporary Array of Last Max. Size .

d. Create new Array with size ( Last Array Size + Increase Value )

e. Copy back values from temp and reference this new array as original array .

f. Must doing Method updates too , need to check it up .

What is Boxing and unboxing? Does it occure automaatically or u need to write code to box and unbox?

Boxing – Process of converting a System.ValueType to Reference Type , Mostly base class System.Object type and allocating it memory on Heap .Reverse is unboxing , but can only be done with prior boxed variables.

Boxing is always implicit but Unboxing needs to be explicitly done via casting , thus ensuring the value type contained inside .

How Boxing and unboxing occures in memory?

Boxing converts value type to reference type , thus allocating memory on Heap . Unboxing converts already boxed reference types to value types through explicit casting , thus  allocating memory on stack .

Why only boxed types can be unboxed?

Unboxing is the process of converting a Reference type variable to Value type and thus allocating memory on the stack . It happens only to those Reference type variables that have been earlier created by Boxing of a Value Type , therefore internally they contain a value type , which can be obtained through explicit casting . For any other Reference type , they don’t internally contain a Value type to Unboxed via explicit casting . This is why only boxed types can be unboxed .

Please read all the post in the Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )