Dynamic Sizing of ASP.Net Textbox

This tip uses the Northwind Database Employee table columns. First – create a connection and a DataReader…
Then, add lines similar to the following, creating variable names for returned items to match your particular sql statement:

While objDR.Read()	strFirst=Trim(objDR("Firstname"))	strLast=Trim(objDR("LastName"))	strTitle=Trim(objDR("Title"))End While

Here’s the function that does the actual work:

Function doLen(item as string)	Dim intWdth as int32	intWdth=item.Length * 7	doLen = Unit.point(intWdth)End Function

(to get better spacing so the ‘*7′ part of the function works better, I optionally added a CSSClass which forces the textbox font to Courier)

Then, inside the ASP.Net TextBox server control, for each one, include the following:
Width=”<%# doLen(varName)%>”

Thanks to DataGridGirl for collaboration on this one.

Configuring a Trusted SQL Srvr Connection in ASP.NET

Following article demonstrates the steps involved in configuring a trusted SQL Server connection to access data using ADO.NET – Written by Shanthanu

Pre-requisites

1. A local instance of SQL Server has to be setup on the same machine as the IIS

2. Optionally, during setup, the SQL server must be configured to be accessible thro’ Windows Authentication Mode. (It doesn’t matter if you haven’t done so)

Step 1: Creating a Trusted SQL Server Connection

For convenience this discussion assumes that an Administrator account is going to be assigned as the trusted SQL Server Connection. (Please read the note at the end of this paper)

sql.server.user.set-1 1.     Open the SQL Server Enterprise Manager from the Windows Start Menu

2.     Navigate to the Security Node under (local)(Windows NT) node that represents the local instance of SQL Server 2000 installed on your computer.

3.     Right-Click the LogIns Node and ClickNew Login.

4. In the SQL Server Login Properties dialog for New Login, click the Browse button against the text box marked Name

untitled 1.     In the next dialog that opens up, select the computer from which the user account has to be chosen from the Drop down list captionedList Names From:

Continues…

DataGrid – Changing the Column Size

Sometimes, it may become necessary to make a DataGrid column more narrow, or wider. This code sample, using the Northwind Database in SQL Server, uses the Employees database to show you just that.

To use this yourself, just copy the code to a new file, change the connection string/database info and you’ve got a running sample!

lt;%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change DataGrid Column Size</title>
<script language=”VB” runat=”server”>
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
Dim strConn as string = “server=(local);uid=UserID;pwd=Password;database=Northwind”
Dim sql as string = “Select FirstName, LastName from Employees”
Dim conn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(sql,conn)
Cmd.Fill(ds,”Employees”)
MyDataGrid.Datasource=ds.Tables(“Employees”).DefaultView
MyDataGrid.DataBind()

end if
End Sub
Sub changesize(Source as Object, E as EventArgs)
Dim intSize as integer
intSize=size.selecteditem.text
MyDataGrid.Columns(0).ItemStyle.Width=Unit.percentage(intSize)
End Sub

</script>
</head>
<body>
<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=”8″
BackColor=”#8080FF”
Font-Name=”Arial”
Font-Bold=”True”
Font-Size=”8″
width=”100%”
BorderColor=”Black”
AutogenerateColumns=”False”>
<Columns>
<asp:BoundColumn DataField=”FirstName” SortExpression=”FirstName” HeaderText=”FirstName”></asp:BoundColumn>
<asp:BoundColumn DataField=”LastName” SortExpression=”LastName” HeaderText=”LastName”></asp:BoundColumn>
</Columns>
</asp:DataGrid>

<asp:dropdownlist id=”size” runat=”server”>
<asp:listitem selected=”true”>10</asp:listitem>
<asp:listitem>20</asp:listitem>
<asp:listitem>30</asp:listitem>
<asp:listitem>50</asp:listitem>
</asp:dropdownlist><b>% </b> <asp:Button id=”button1″ Text=”change size” onclick=”changesize” runat=”server” />
</form>
</body>
</html>

ASP.Net Server Controls Not Showing on pages

It’s possible that ASP.Net is not registered correctly on your system.
Try running aspnet_regiis from the command prompt.

Here’s the default location:

C:\WINNT\Microsoft.NET\Framework\<<ASP.Net Version#>>\aspnet_regiis.exe -i

Windows Server 2003, you must use aspnet_regiis -i -enable
This is because of the “Web Service Extensions” feature in IIS 6

(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET ‘hooks’ into IIS properly.”

Adding Dynamic Content to Your Pages in ASP.NET

In a data-driven website, there becomes a need to have only one page serve up different data, based on the call to the database. Naturally, you wouldn’t want to have the same Title on the page’s drag bar, and you certainly would like to have different Keywords in your meta tag along with every section of content received from the database. This tutorial will attempt to provide a simple example/overview of how to dynamically add, not only the content, but the Title of the page and the Keywords for the HTML Meta Tags in order to get you started in this direction.

First we’ll start with the database table structure. Keep in mind, I previously said ‘a simple way’, so, keeping that in mind, here would be four fields needed to do this:

  • id (in MS Access, Autonumber/in SQL Server – Identity)
  • Title
  • Keywords
  • Content – content for the page

For each section of content we plan to show in this page, when we enter the data into the table, we will, of course, make the fields not accept nulls.Since the ID field is autonumbering, we don’t need to worry about that field when inserting data. When we call this page (let’s call it ‘Content.aspx’), it will need a querystring added to it, which will be based on the ID field – something like ‘Content.aspx?id=1″. This way, we will then query the database in the Page_Load event, requesting record #1 from our table. it will then return the Title, Keys and the Content for the page. Outside of Page_Load, we dimension the variables:

Dim sKeys, sTitle, sContent as String

We’ll only need a DataReader to retrieve this information, and we can put the information into variables for use within the page, like this:

While objDR.Read
	sContent=objDR("Content")
	sTitle=objDR("Title")
	sKeys=objDR("keywords")
End While

Continues…

DataGrid – Changing Page Size (# of Rows) Programmatically

Sometimes, you may find the need to change the number of rows shown on a DataGrid programmatically. The number of rows is known as the page size. This code sample shows how to do this using the Northwind Database customers table.

Just copy the code to your new page, change the connection string to your SQL Server and you’re up and running!

<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<!– Created: 8/14/2002 12:02:04 PM –>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change DataGrid Page Size</title>
<script language=”VB” runat=”server”>
Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub

Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
BindData()
End If
End Sub

Sub changepagesize(Source as Object, E as EventArgs)
dosize
End Sub

Sub dosize()
if pagesize.selecteditem.text <>”" then
MyDataGrid.pagesize=pagesize.selecteditem.text
End If
With MyDataGrid
Try
binddata
Catch
.currentpageindex=0
finally
binddata
End Try
end with

End Sub

Sub BindData()
Dim strConn as string = “(local);uid=userID;pwd=pwd;database=Northwind”
Dim sql as string = “Select CustomerID, CompanyName, ContactName, Phone from Customers”
Dim conn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(sql,conn)
Cmd.Fill(ds,”Customers”)
MyDataGrid.Datasource=ds.Tables(“Customers”).DefaultView
MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<div align=”center”><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=”10″
BackColor=”#8080FF”
Font-Name=”Arial”
Font-Bold=”True”
Font-Size=”10″
BorderColor=”Black”
AllowPaging = “True”
PagerStyle-Mode = “NumericPages”
OnPageIndexChanged = “Page_Change”
AutogenerateColumns=”False”>
<Columns>
<asp:BoundColumn DataField=”CustomerID” SortExpression=”CustomerID” HeaderText=”CustomerID”></asp:BoundColumn>
<asp:BoundColumn DataField=”CompanyName” SortExpression=”CompanyName” HeaderText=”CompanyName”></asp:BoundColumn>
<asp:BoundColumn DataField=”ContactName” SortExpression=”ContactName” HeaderText=”ContactName”></asp:BoundColumn>
<asp:BoundColumn DataField=”Phone” SortExpression=”Phone” HeaderText=”Phone”></asp:BoundColumn>
</Columns>
</asp:DataGrid>
<table> <tr>
<td align=”center” valign=”Top”><b><i>Change Page Size:</i></b>
<asp:dropdownlist id=”pagesize” runat=”server” autopostback=”true” OnSelectedIndexChanged=”changepagesize”>
<asp:listitem selected=”true”></asp:listitem>
<asp:listitem>5</asp:listitem>
<asp:listitem>10</asp:listitem>
<asp:listitem>15</asp:listitem>
<asp:listitem>20</asp:listitem>
<asp:listitem>30</asp:listitem>
<asp:listitem>40</asp:listitem>
</asp:dropdownlist> <i>(number of rows shown in DataGrid)</i></td>
</tr>
</table>
</form></div>

</body>
</html>

Add Item to Bound DropDownList

To add an item to the top of a DropDownList at any time, here’s the code:
MyDDL.items.insert(0,”WhateverYouWantHERE”)

The ’0′ shows that it needs to insert the item at the top position of the DropDownList item collection. The second part, “WhateverYouWantHERE” is the actual text you want displayed. You could also use this to put a blank item at the top:
MyDDL.items.insert(0,”")

or to specify both value and text:
Dim liItem as ListItem=New ListItem(“text”, “value”)
MyDDL.Items.Insert(0, liItem)

Menu User Control with Rollovers in ASP.NET

Many people have asked about using Rollover button images in Forums and ListServs lately. Therefore, this tutorial will attempt to explain how to create a menu system as a user control, using Javascript Rollover images. If you’ve read any of the tutorials on this site before, you know how many times they’ve started out with something like, “This is not going to be as hard as it sounds”. Well, this time is no exception.

If you’ve ever used an HTML/Javascript solution for creating Javascript Rollover Buttons, you know how complicated it can get if you’re not using an editor that will help you do it. Technically, the way that is about to be explained uses the same Javascript principles, but in a much less complex way.

First, we start out with creating a new User Control. Call it menu.ascx. You can create the visual portion anyway you want it – vertically or horizontally, in a Table or not. However, today, we’re creating one in an HTML table, horizontally. In our new menu, there will be three buttons, Art, Contact and Web Design. Keep in mind here, that, for each of these three menu buttons, you will need to create 3 buttons for the different ‘States’ of the buttons (basic, OnMouseOver, OnMouseDown). As you can see, at this point, this tutorial is going a little bit further than just having a ‘Hover’ or ‘OnMouseOver’ state. the ‘OnMouseDown’ state is for two things – when the button is clicked, and defining a button for when the page relating to the button is the current open page.

Continues…

Arraylist – Adding Items/Sorting/Binding

This code sample shows how to add items dynamically, to an arraylist, which is assigned to a Session, and then sort (ascending) the items once new items are added. Another button is there for sorting in descending order

The arraylist is bound, in this case, to a listbox, although a dropdownlist would work just the same.

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>ArrayList</title>
<script language=”VB” runat=”server”>
Dim colshoppingList as ArrayList
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
colshoppingList=New Arraylist
colshoppingList.add(“eggs”)
colshoppingList.add(“milk”)
colshoppingList.add(“bread”)
colshoppingList.add(“corn”)
lb1.datasource=colshoppingList
lb1.databind
Session(“colShop”)=colshoppingList
end if
End Sub

Sub doSort(Source as Object, E as EventArgs)
Session(“colShop”).sort
lb1.datasource=Session(“colShop”)
lb1.databind
End Sub

Sub DoDesc(Source as Object, E as EventArgs)
Session(“colShop”).sort
Session(“colShop”).reverse
lb1.datasource=Session(“colShop”)
lb1.databind
End Sub

Sub addit(Source as Object, E as EventArgs)
Dim strItem as string
strItem=text1.text
Session(“colShop”).add(strItem)
text1.text=”"
lb1.datasource=Session(“colShop”)
lb1.databind
End Sub
</script>
</head>
<body>

<Form id=”form1″ runat=”server”>
<asp:ListBox id=”LB1″ SelectionMode=”Single” runat=”server” /><br>

<asp:TextBox id=”text1″ runat=”server” /> <asp:Button id=”button2″ Text=”AddItem” onclick=”Addit” runat=”server” />
<p>
<asp:Button id=”button1″ Text=”Sort ASC” onclick=”doSort” runat=”server” /> <asp:Button id=”button3″ Text=”Sort DESC” onclick=”DoDesc” runat=”server” />
</Form>

</body>
</html>

Check DB to see if Records exist

When inserting a record into the database, it’s always better if it’s not entered a second time by an unsteady index finger.

To make sure this doesn’t happen – with the existing data, query the database first to see if it exists, then, if it doesn’t exist, then go ahead and enter the information.