Color Picker in ASP.NET

Microsoft has confirmed a bug, saying that the attributes property of ListItem will not work in the DropDownlist(i.e Web server Control).
The alternative for this is to use HTML Server Control
So we then would do is as below:

<SELECT id="DropDownList1" name="DropDownList1" runat="server"> </SELECT>

Using this control we’ll change the background Color of each Item in DropDown.

private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!IsPostBack) { foreach(FieldInfo col in typeof( KnownColor).GetFields() ) { if (col.FieldType == typeof(KnownColor) ) { DropDownList1.Items.Add(new ListItem(col.Name ,col.Name)); } } } for (int i= 0 ;i < DropDownList1.Items.Count;i++) { DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text); } }

Make sure to Import the System.Reflections namespace, as well as the System.Drawing namespace, for this example

A Beginners Guide to the HyperinkField

At first glance, the HyperlinkField (used in the GridView) seems fairly straightforward, but on second glance, you might be a little intimidated on how to use it. In this tutorial, we’ll be only focusing on using it in a Gridview which is being populated by a database, so the properties we’ll be looking at will be fewer.

The main concept of the HyperLinkField is to act as a regular HTML hyperlink in your Gridview, using data retrieved dynamically from your datasource.

The four main properties into which we’ll be looking are the DataTextField, HeaderText, DataNavigateURLFields, and DataNavigateUrlFormatString.

We’ll get HeaderText out of the way first since it’s the simplest of all of them. This, of course, is what appears in the Header of the Gridview, atop the HyperlinkField’s column. You can change it any way you’d like and it won’t affect anything else in your data retrieval

Next, we’ll look at the DataTextField. This, too, is fairly straight-forward. It will be what is actually displayed in each row, using the data retrieved from the datasource. For instance, if you’re field/column is from the FirstName field in your database, then, it would display Tom, Cathy, David, etc.

The last two properties at which we’re looking interact with each other. First, think of a link you have to another page. If it were a regular HTML hyperlink, you’d have something like this:
Report
Now, think of this in terms of adding a querystring to the url:
Report

In a Gridview scenario, this column, in each row, could have a different actual querystring based on particular results retrieved from the database in that record. In this scenario, you’d want the actual URL to be the same URL for each record, but the querystring ‘ID’ would be different. For the purpose of this scenario, let’s say the ‘ID’ is coming from a field in the database called ‘MasterID’.

Therefore, to do this, we’d set the DataTextField property to MasterID (which will display the number itself), and we’d set the DataNavigateURLFields property to MasterID (this sets the querystring). Next, in order to get the complete URL (Report.aspx?id=27), we’d also set the DataNavigateURLFormatString to Report.aspx?id={0}. We also need to make sure that the exact path is listed here, so if the Report.aspx file is in a different folder, that needs to be reflected here. Having {0} at the end, tells it to use whatever is listed in the DataNaviageURLFields property for the querystring. That’s basically all there is to it.

So, you’d end up with something like this:
Continues…

ListBox – Select All/Select None

This code sample takes another code sample on the site (2 Listboxes – Moving Items From One to Another) and enhances it. Here, we also show how to add ‘Select All/Select None’ functionality for each listbox.

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.0">
	<title>ListBox - Select All/Select None</TITLE>
	<Link REL=STYLESHEET HREF="/basicArial.css" TYPE="text/css">

<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
        If Not Page.IsPostBack Then
            Dim intFirst As Integer
            For intFirst = 1 To 10
                ListBox1.Items.Add("Item " & intFirst)
            Next
        End If
End Sub

Sub button1_click(Source as Object, E as EventArgs)
        Dim li As ListItem
        For Each li In ListBox1.Items
            If li.Selected = True Then
                ListBox2.Items.Add(li.Text)
            End If
        Next

        Dim counter As Integer
        For counter = (ListBox1.Items.Count - 1) To 0 Step -1
            If ListBox1.Items(counter).Selected = True Then
                ListBox1.Items.RemoveAt(counter)
            End If
       Next
End Sub

Sub button2_click(Source as Object, E as EventArgs)
        Dim counter As Integer
        Dim li As ListItem

        For Each li In ListBox2.Items
            If li.Selected = True Then
                ListBox1.Items.Add(li.Text)
            End If
        Next

        For counter = (ListBox2.Items.Count - 1) To 0 Step -1
            If ListBox2.Items(counter).Selected = True Then
                ListBox2.Items.RemoveAt(counter)
            End If
        Next
End Sub
Sub selAll(Source as Object, E as EventArgs)
	Dim liAll As ListItem
	Dim sList as ListBox
	if Source.id="lbSelectAll" then
		sList=ListBox1
	else
		sList=ListBox2
	End If
        	For Each liAll In sList.Items
	liAll.Selected=true
        Next
End Sub
Sub selNone(Source as Object, E as EventArgs)
        	Dim liAll As ListItem
	Dim sList as ListBox
	if Source.id="lbSelectNone" then
		sList=ListBox1
	else
		sList=ListBox2
	End If
        For Each liAll In sList.Items
	liAll.Selected=false
        Next
End Sub

</script>
</head>
<body>
<div align="center"><Form id="form1" runat="server">
<table  cellpadding="2" cellspacing="2" border=0>
	<tr>
		<td align="center" valign="top">
<asp:ListBox id="ListBox1"
width="125px" height="175"
SelectionMode="Multiple" runat="server" /><br>
Select : <asp:LinkButton id="lbSelectAll"
Text="All" onclick="SelAll" runat="server" />
<asp:LinkButton id="lbSelectNone" Text="None" onclick="selNone" runat="server" /></td>
		<td align="center" valign="center">
<asp:Button id="button1"
width="88px" height="26"
Text="Add >>" onclick="button1_click" runat="server" /><br>
<asp:Button id="button2"
Text="<< Remove" onclick="button2_click"
width="88px" height="26" runat="server" />
		</td>
		<td align="center" valign="top">
<asp:ListBox id="Listbox2" width="125px" height="175"
SelectionMode="Multiple" runat="server" /><br>
Select : <asp:LinkButton id="lb2SelectAll"
Text="All" onclick="SelAll" runat="server" />
<asp:LinkButton id="lb2SelectNone" Text="None" onclick="selNone" runat="server" /></td>
	</tr>
</table>

</Form></div>
</body>
</html>

Page Level Impersonation in ASP.NET

Sometimes, Global Impersonation in the website is not the right solution, however, it is possible to provide Impersonation at the page level. To do this, you can provide Impersonation for the page, using the current logged in identity of the person viewing the page. One specific need in which this might be handy, is a situation in which your website has an ASPX page, using the System.IOnamespace, and you’re dynamically getting a file listing from another server.

To start, you need to provide/dimension a couple of variables, with a page level scope:

Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity

Page level scope‘ means, basically, that you do not include these statements within an event handler. They’re normally put at the top of the document. If you’re using a <script> tag, put them just inside the tag. If you’re using code-behind, put them inside the class signature, and outside the event handlers. Of course, you should put all your code inside a Try/Catch block, and, for the sake of this Tutorial, we’ll assume that you’ll be using Impersonation inside the Page_Load event. The next bit of code you’d need, would be the parts that actually do the Impersonation:

currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity) impersonationContext = currentWindowsIdentity.Impersonate()

This uses User.Identity (the currently logged in user), and sets the Impersonation to that person. The last thing we would want to do is to remove the Impersonation, immediately after the need has been removed. In this case, once the list of files has been received and displayed, we have no more need for setting Impersonation, so we’d need to remove it. To do this, it’s only one line of code:

impersonationContext.Undo()

So, then, the final way the code would look is as follows:
Continues…

Simple Scrollable DataGrid

Here’s perhaps the simplest way to add scroll-ability to your DataGrid. It’s accomplished by adding your DataGrid inside DIV tags, with overflow set to scroll. You’ll probably need to fool around with the width and height for your particular uses, but it’s pretty cool little trick I found in several places, including the ASP.Net/forums. It boils down to these two facts:
If you assign the width of the Div smaller than the DataGrid, you automatically have horizontal scroll bars.
If you make the height of the Div smaller than the height of the DataGrid, then you automatically have vertical scrollbars.

This sample uses the SQL Server managed provider and the Northwind Database with the Products Table. In order to try this on your system, just copy the code directly from the page, paste it into a new page on your computer, change the connection string to match your system and you’re on your way.

To try this with the OleDb managed provider, copy the code and pasted it into our Database Code Conversion Tool before you do the steps listed in the last paragraph.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Simple Scrollable DataGrid</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select Products.ProductName, Products.QuantityPerUnit, " & _
"Products.UnitPrice, Products.UnitsInStock from Products"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	MyDataGrid.DataSource = objDR
	MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<div id="Layer1" style="position:relative;width:450px; height:300px;overflow: scroll;">
<form runat="server" method="post">
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Bold="True"
	Headerstyle-Font-Size="12"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="10"
	AlternatingItemStyle-BackColor="#DFDFDF"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="10"
	BorderColor="Black"
	AutogenerateColumns="False">
	<Columns>
		<asp:BoundColumn
			DataField="ProductName"
			HeaderText="ProductName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="QuantityPerUnit"
			HeaderText="QuantityPerUnit">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="UnitPrice"
			HeaderText="UnitPrice">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="UnitsInStock"
			HeaderText="UnitsInStock">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>

</form>
</div>
</body>
</html>

Inserting and Updating with a SQLDataSource

In most SQLDataSource articles, the data display is usually a Gridview, or a DetailsView. However, in this tutorial, we’re going to look at how to provide Inserting and Updating functions within a page with single-field type controls (TextBox/DropDownList, etc). Sometimes, for simpler pages, these types of controls are a bit overkill, or even with more complex pages where they don’t seem to fit the bill., you might need a more freehand approach

I’m going to use a very simple Insert sample here, with just two textboxes, but you can use any other controls you’d like. In the ASPX page, let’s insert two textboxes and some text, for labeling what should be put in the textboxes, just as you’d see on an average web page, along with a button:

First Name:
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
Last Name:
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

Of course, in our imaginary scenario, we’d have a table in the database (let’s call it ‘Test_Table’), with only two columns (Firstname, and Lastname). And along with this, we’d have a stored procedure called ‘Insert_Test’, with two parameters:

CREATE PROCEDURE [dbo].[Insert_Test]
@FirstName varchar(50),
@LastName varchar(50)

AS
Insert into Test_New (FirstName, LastName)
Values (@FirstName, @LastName)

Next, we’ll add a SQLDataSource control, and just call it ‘DS1′:

 <asp:SqlDataSource ID="ds1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyTest_dbConnectionString %>"
InsertCommand="Insert_Test"
InsertCommandType="StoredProcedure"
SelectCommand="Select * from Test">
<InsertParameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
</InsertParameters>
</asp:SqlDataSource>

For the click event of the ‘Submit’ button, we’ll just put in one line:
Continues…

Enhanced Calendar/Database with MS Access

This is the same calendar code as that posted earlier, using SQL Server. However, this time, it was run through the Database Code Converter Tool on the ASPNet101.com site to convert it from the SQL Server Managed Provider to the OleDb Managed Provider.

To download the zipped MS Access Database to work with this, Download Here. Then, to get this working on your system, just copy this code to a new file on your computer, change the connection string to match the path on your computer.