Visual Basic Q&A

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘microsoft knowledge base’

How to automate Microsoft Excel from Visual Basic .NET

Symptoms
This article demonstrates how to create an Automation client for Microsoft Excel by using Microsoft Visual Basic .NET.
Resolution
Automation is a process that allows applications that are written in languages such as Visual Basic to programmatically control other applications. Automation to Excel allows you to perform actions such as creating a new workbook, adding data to the workbook, or creating charts. With Excel and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using Automation.
Excel exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Excel. For example, there is an Application object, a Workbook object, and a Worksheet object, each of which contain the functionality of those components of Excel. To access the object model from Visual Basic .NET, you can set a project reference to the type library.
This article demonstrates how to set the proper project reference to the Excel type library for Visual Basic .NET and provides sample code to automate Excel. Create an automation client for Microsoft ExcelStart Microsoft Visual Studio .NET.On the File menu, click New, and then click Project. Select Windows Application from the Visual Basic Project types. Form1 is created by default.Add a reference to Microsoft Excel Object Library. To do this, follow these steps: On the Project menu, click Add Reference.On the COM tab, locate Microsoft Excel Object Library, and then click Select.
Note Microsoft Office 2003 includes Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they can be downloaded. For more information about Office XP PIAs, click the following article number to view the article in the Microsoft Knowledge Base:
328912?(http://support.microsoft.com/kb/328912/) Microsoft Office XP primary interop assemblies (PIAs) are available for downloadClick OK in the Add References dialog box to accept your selections.On the View menu, select Toolbox to display the Toolbox, and then add a button to Form1.Double-click Button1. The code window for the form appears.In the code window, locate the following code:

Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickEnd Sub Replace the previous code with the following code:

Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickDim oXL As Excel.ApplicationDim oWB As Excel.WorkbookDim oSheet As Excel.WorksheetDim oRng As Excel.Range’ Start Excel and get Application object.oXL = CreateObject(“Excel.Application”)oXL.Visible = True’ Get a new workbook.oWB = oXL.Workbooks.AddoSheet = oWB.ActiveSheet’ Add table headers going cell by cell.oSheet.Cells(1, 1).Value = “First Name”oSheet.Cells(1, 2).Value = “Last Name”oSheet.Cells(1, 3).Value = “Full Name”oSheet.Cells(1, 4).Value = “Salary”‘ Format A1:D1 as bold, vertical alignment = center.With oSheet.Range(“A1″, “D1″).Font.Bold = True.VerticalAlignment = Excel.XlVAlign.xlVAlignCenterEnd With’ Create an array to set multiple values at once.Dim saNames(5, 2) As StringsaNames(0, 0) = “John”saNames(0, 1) = “Smith”saNames(1, 0) = “Tom”saNames(1, 1) = “Brown”saNames(2, 0) = “Sue”saNames(2, 1) = “Thomas”saNames(3, 0) = “Jane”saNames(3, 1) = “Jones”saNames(4, 0) = “Adam”saNames(4, 1) = “Johnson”‘ Fill A2:B6 with an array of values (First and Last Names).oSheet.Range(“A2″, “B6″).Value = saNames’ Fill C2:C6 with a relative formula (=A2 & ” ” & B2).oRng = oSheet.Range(“C2″, “C6″)oRng.Formula = “=A2 & “” “” & B2″‘ Fill D2:D6 with a formula(=RAND()*100000) and apply format.oRng = oSheet.Range(“D2″, “D6″)oRng.Formula = “=RAND()*100000″oRng.NumberFormat = “$0.00″‘ AutoFit columns A:D.oRng = oSheet.Range(“A1″, “D1″)oRng.EntireColumn.AutoFit()’ Manipulate a variable number of columns for Quarterly Sales Data.Call DisplayQuarterlySales(oSheet)’ Make sure Excel is visible and give the user control’ of Excel’s lifetime.oXL.Visible = TrueoXL.UserControl = True’ Make sure that you release object references.oRng = NothingoSheet = NothingoWB = NothingoXL.Quit()oXL = NothingExit SubErr_Handler:MsgBox(Err.Description, vbCritical, “Error: ” & Err.Number)End SubPrivate Sub DisplayQuarterlySales(ByVal oWS As Excel.Worksheet)Dim oResizeRange As Excel.RangeDim oChart As Excel.ChartDim oSeries As Excel.SeriesDim iNumQtrs As IntegerDim sMsg As StringDim iRet As Integer’ Determine how many quarters to display data for.For iNumQtrs = 4 To 2 Step -1sMsg = “Enter sales data for” & Str(iNumQtrs) & ” quarter(s)?”iRet = MsgBox(sMsg, vbYesNo Or vbQuestion _Or vbMsgBoxSetForeground, “Quarterly Sales”)If iRet = vbYes Then Exit ForNext iNumQtrs’ Starting at E1, fill headers for the number of columns selected.oResizeRange = oWS.Range(“E1″, “E1″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=”"Q”" & COLUMN()-4 & CHAR(10) & “”Sales”"”‘ Change the Orientation and WrapText properties for the headers.oResizeRange.Orientation = 38oResizeRange.WrapText = True’ Fill the interior color of the headers.oResizeRange.Interior.ColorIndex = 36′ Fill the columns with a formula and apply a number format.oResizeRange = oWS.Range(“E2″, “E6″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=RAND()*100″oResizeRange.NumberFormat = “$0.00″‘ Apply borders to the Sales data and headers.oResizeRange = oWS.Range(“E1″, “E6″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin’ Add a Totals formula for the sales data and apply a border.oResizeRange = oWS.Range(“E8″, “E8″).Resize(ColumnSize:=iNumQtrs)oResizeRange.Formula = “=SUM(E2:E6)”With oResizeRange.Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble.Weight = Excel.XlBorderWeight.xlThickEnd With’ Add a Chart for the selected data.oResizeRange = oWS.Range(“E2:E6″).Resize(ColumnSize:=iNumQtrs)oChart = oWS.Parent.Charts.AddWith oChart.ChartWizard(oResizeRange, Excel.XlChartType.xl3DColumn, , Excel.XlRowCol.xlColumns)oSeries = .SeriesCollection(1)oSeries.XValues = oWS.Range(“A2″, “A6″)For iRet = 1 To iNumQtrs.SeriesCollection(iRet).Name = “=”"Q” & Str(iRet) & “”"”Next iRet.Location(Excel.XlChartLocation.xlLocationAsObject, oWS.Name)End With’ Move the chart so as not to cover your data.With oWS.Shapes.Item(“Chart 1″).Top = oWS.Rows(10).Top.Left = oWS.Columns(2).LeftEnd With’ Free any references.oChart = NothingoResizeRange = NothingEnd Sub Add the following code to the top of Form1.vb:

Imports Microsoft.Office.Core Test the automation clientPress F5 to build and to run the program.On the form, click Button1. The program starts Excel and populates data on a new worksheet.When you are prompted to enter quarterly sales data, click Yes. A chart that is linked to quarterly data is added to the worksheet.

How to automate Excel from Visual Basic .NET to fill or to obtain data in a range by using arrays

Symptoms
This article demonstrates how to automate Microsoft Excel and how to fill a multi-cell range with an array of values. This article also illustrates how to retrieve a multi-cell range as an array by using Automation.
Resolution
To fill a multi-cell range without populating cells one at a time, you can set the Value property of a Range object to a two-dimensional array. Likewise, a two-dimensional array of values can be retrieved for multiple cells at once by using the Value property. The following steps demonstrate this process for both setting and retrieving data using two-dimensional arrays. Build the Automation Client for Microsoft ExcelStart Microsoft Visual Studio .NET.On the File menu, click New, and then click Project. Select Windows Application from the Visual Basic Project types. By default, Form1 is created.Add a reference to Microsoft Excel Object Library. To do this, follow these steps: On the Project menu, click Add Reference.On the COM tab, locate Microsoft ExcelObject Library, and then click Select.
Note Microsoft Office 2007 and Microsoft Office 2003 include Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they can be downloaded.
For additional information about Office XP PIAs, click the article number below to view the article in the Microsoft Knowledge Base:
328912?(http://support.microsoft.com/kb/328912/EN-US/) INFO: Microsoft Office XP PIAs Are Available for DownloadClick OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click Yes.On the View menu, select Toolbox to display the Toolbox. Add two buttons and a check box to Form1.Set the Name property for the check box to FillWithStrings.Double-click Button1. The code window for the Form appears.Add the following to the top of Form1.vb:

Imports Microsoft.Office.Interop In the code window, replace the following code

Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickEnd Sub with:

‘Keep the application object and the workbook object global, so you can’retrieve the data in Button2_Click that was set in Button1_Click.Dim objApp As Excel.ApplicationDim objBook As Excel._WorkbookPrivate Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickDim objBooks As Excel.WorkbooksDim objSheets As Excel.SheetsDim objSheet As Excel._WorksheetDim range As Excel.Range’ Create a new instance of Excel and start a new workbook.objApp = New Excel.Application()objBooks = objApp.WorkbooksobjBook = objBooks.AddobjSheets = objBook.WorksheetsobjSheet = objSheets(1)’Get the range where the starting cell has the address’m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.range = objSheet.Range(“A1″, Reflection.Missing.Value)range = range.Resize(5, 5)If (Me.FillWithStrings.Checked = False) Then’Create an array.Dim saRet(5, 5) As Double’Fill the array.Dim iRow As LongDim iCol As LongFor iRow = 0 To 5For iCol = 0 To 5′Put a counter in the cell.saRet(iRow, iCol) = iRow * iColNext iColNext iRow’Set the range value to the array.range.Value = saRetElse’Create an array.Dim saRet(5, 5) As String‘Fill the array.Dim iRow As LongDim iCol As LongFor iRow = 0 To 5For iCol = 0 To 5′Put the row and column address in the cell.saRet(iRow, iCol) = iRow.ToString() + “|” + iCol.ToString()Next iColNext iRow’Set the range value to the array.range.Value = saRetEnd If’Return control of Excel to the user.objApp.Visible = TrueobjApp.UserControl = True’Clean up a little.range = NothingobjSheet = NothingobjSheets = NothingobjBooks = NothingEnd Sub Return to the design view for Form1, and then double-click Button2.In the code window, replace the following code

Private Sub Button2_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button2.ClickEnd Sub with:

Private Sub Button2_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button2.ClickDim objSheets As Excel.SheetsDim objSheet As Excel._WorksheetDim range As Excel.Range’Get a reference to the first sheet of the workbook.On Error Goto ExcelNotRunningobjSheets = objBook.WorksheetsobjSheet = objSheets(1)ExcelNotRunning:If (Not (Err.Number = 0)) ThenMessageBox.Show(“Cannot find the Excel workbook.Try clicking Button1 to ” + _”create an Excel workbook with data before running Button2.”, _”Missing Workbook?”)’We cannot automate Excel if we cannot find the data we created,’so leave the subroutine.Exit SubEnd If’Get a range of data.range = objSheet.Range(“A1″, “E5″)’Retrieve the data from the range.Dim saRet(,) As ObjectsaRet = range.Value’Determine the dimensions of the array.Dim iRows As LongDim iCols As LongiRows = saRet.GetUpperBound(0)iCols = saRet.GetUpperBound(1)’Build a string that contains the data of the array.Dim valueString As StringvalueString = “Array Data” + vbCrLfDim rowCounter As LongDim colCounter As LongFor rowCounter = 1 To iRowsFor colCounter = 1 To iCols’Write the next value into the string.valueString = String.Concat(valueString, _saRet(rowCounter, colCounter).ToString() + “, “)Next colCounter’Write in a new line.valueString = String.Concat(valueString, vbCrLf)Next rowCounter’Report the value of the array.MessageBox.Show(valueString, “Array Values”)’Clean up a little.range = NothingobjSheet = NothingobjSheets = NothingEnd Sub Test the Automation ClientPress F5 to build and to run the sample program.Click Button1. Microsoft Excel is started with a new workbook, and cells A1:E5 of the first worksheet are populated with numeric data from an array.Click Button2. The program retrieves the data in cells A1:E5 into a new array and displays the results in a message box.Select FillWithStrings, and then click Button1 to fill cells A1:E5 with the string data.

ASP.NET data binding overview

Symptoms
This article provides an introduction to ASP.NET data binding.
For additional ASP.NET overviews, see the following Microsoft Knowledge Base article:
305140?(http://support.microsoft.com/kb/305140/) ASP.NET roadmap
Resolution
With ASP.NET data binding, you can bind any server control to simple properties, collections, expressions and/or methods. When you use data binding, you have more flexibility when you use data from a database or other means.
This article addresses the following data binding topics: Data binding essentials<%# %> SyntaxPage.DataBind() versus Control.DataBind()Data-bound list controlsRepeater controlDataList controlDataGrid controlAccessing dataDataSet dlassDataReader dlassBinding in list control templatesDataBinder.Eval methodExplicit castingItemDataBound event
Data binding essentials<%# %> Syntax ASP.NET introduces a new declarative syntax, <%# %>. This syntax is the basis for using data binding in an .aspx page. All data binding expressions must be contained within these characters. The following list includes examples of simple data binding from multiple sources: Simple property (syntax for a customer):

<%# custID %> Collection (syntax for an order):

<asp:ListBox id=”List1″ datasource=’<%# myArray %>’ runat=”server”> Expression (syntax for a contact):

<%# ( customer.First Name + ” ” + customer.LastName ) %> Method result (syntax for the outstanding balance):

<%# GetBalance(custID) %> In the preceding examples, the inline <%# %> tags indicate where the information from a specific data source is to be placed in the .aspx page. The following data binding example uses a TextBox Web server control:

<asp:textbox id=txt text=”<%# custID %>” runat=server /> For more information about data binding syntax, see the following .NET Framework Software Development Kit (SDK) documentation:
Data Binding Expression Syntax
http://msdn2.microsoft.com/en-us/library/bda9bbfx(vs.71).aspx(http://msdn2.microsoft.com/en-us/library/bda9bbfx(vs.71).aspx)Page.DataBind() versus Control.DataBind() After the particular data sources have been determined and set for the objects on the .aspx page, you must bind the data to these data sources. You can use the Page.DataBind or the Control.DataBind method to bind the data to the data sources.
Both methods work similarly. The main difference is that all data sources are bound to their server controls after the Page.DataBind method is called. No data is rendered to the control until you explicitly call either the DataBind method of the Web server control or until you invoke the page-level Page.DataBind method. Typically, Page.DataBind (or DataBind) is called from the Page_Load event.
For more information about the DataBind method, see the following .NET Framework SDK documentation: Control.DataBind Method
http://msdn.microsoft.com/en-us/library/w5e5992d.aspx(http://msdn.microsoft.com/en-us/library/w5e5992d.aspx)
Data-bound list controls The list controls are special Web server controls that can bind to collections. You can use these controls to display rows of data in a customized template format. All list controls expose the DataSource and the DataMember properties, which are used to bind to collections.
These controls can bind their DataSource property to any collection that supports the IEnumerable, the ICollection, or the IListSource interface.
Repeater control The Repeater control is a templated, data-bound list. The Repeater control is “lookless;” that is, it does not have any built-in layout or styles. Therefore, you must explicitly declare all HTML layout, formatting, and style tags in the control’s templates.
The following code samples demonstrate how you can use one list control, the Repeater control, to display data:
NOTE: You must modify the parameters of the connection string as necessary for your environment.
Visual Basic .NET

<%@ Page Language=”vb” %><%@ Import Namespace=”System.Data” %><%@ Import Namespace=”System.Data.SqlClient” %><script runat=”server”>Sub Page_Load(sender As Object, e As EventArgs)Dim cnn As SqlConnection = New SqlConnection(“server=(local);” & _”database=pubs;Integrated Security=SSPI”)Dim cmd As SqlDataAdapter = New SqlDataAdapter(“select * from authors”, cnn)Dim ds As DataSet = New DataSet()cmd.Fill(ds)Repeater1.DataSource = dsRepeater1.DataBind()End Sub</script><html><body><form id=”Form1″ method=”post” runat=”server”><asp:Repeater id=”Repeater1″ runat=”server”><ItemTemplate><%# DataBinder.Eval(Container.DataItem,”au_id”) %><br> </ItemTemplate></asp:Repeater></form></body></html> Visual C# .NET

<%@ Page language=”c#” %><%@ Import Namespace=”System.Data” %><%@ Import Namespace=”System.Data.SqlClient” %><script runat=”server”>void Page_Load(Object sender, EventArgs e) {SqlConnection cnn = newSqlConnection(“server=(local);database=pubs;Integrated Security=SSPI”);SqlDataAdapter da = new SqlDataAdapter(“select * from authors”, cnn);DataSet ds = new DataSet();da.Fill(ds, “authors”);Repeater1.DataSource = ds.Tables["authors"];Repeater1.DataBind();}</script><html><body><form id=”WebForm2″ method=”post” runat=”server”><asp:Repeater id=”Repeater1″ runat=”server”><ItemTemplate><%# DataBinder.Eval(Container.DataItem,”au_id”) %><br> </ItemTemplate></asp:Repeater></form></body></html> Visual J# .NET

<%@ Page language=”VJ#” %><%@ Import Namespace=”System.Data” %><%@ Import Namespace=”System.Data.SqlClient” %> <script runat=”server”>void Page_Load(Object sender, EventArgs e) {SqlConnection cnn = new SqlConnection(“server=(local);database=pubs;IntegratedSecurity=SSPI”);SqlDataAdapter da = new SqlDataAdapter(“select * from authors”, cnn);DataSet ds = new DataSet();da.Fill(ds, “authors”);DataTableCollection dtc = ds.get_Tables();int index = dtc.IndexOf(“authors”);Repeater1.set_DataSource(dtc.get_Item(index));Repeater1.DataBind();}</script><html><body><form id=”WebForm2″ method=”post” runat=”server”><asp:Repeater id=”Repeater1″ runat=”server”><ItemTemplate><%# DataBinder.Eval(Container.DataItem,”au_id”) %><br></ItemTemplate></asp:Repeater></form></body></html> For more information about the Repeater control, see the following .NET Framework SDK documentation:
Repeater Web Server Control
http://msdn.microsoft.com/en-us/library/x8f2zez5.aspx(http://msdn.microsoft.com/en-us/library/x8f2zez5.aspx)DataList control The DataList class is a feature-rich, templated, data-bound list. You can modify the templates to customize this control. Unlike the Repeater control, DataList supports directional rendering and can optionally render in an HTML table at run time.
For more information about the DataList control, see the following .NET Framework SDK documentation:
DataList Web Server Control
http://msdn.microsoft.com/en-us/library/9cx2f3ks(VS.85).aspx(http://msdn.microsoft.com/en-us/library/9cx2f3ks(VS.85).aspx)DataGrid control The DataGrid control is a fully featured, multicolumn, data-bound grid. To customize the layout of individual columns in the DataGrid, you can set the column type to “templated” and modify the column’s templates. The DataGrid control can render without templates, which makes this control ideal for reporting scenarios. DataGrid also supports selection, editing, deletion, paging, and sorting by column and button columns.
For more information about the DataGrid control, see the following .NET Framework SDK documentation:
DataGrid Web Server Control
http://msdn.microsoft.com/en-us/library/aa710742(VS.71).aspx(http://msdn.microsoft.com/en-us/library/aa710742(VS.71).aspx)
Accessing data This section describes how to access data from a database and bind the data to list controls. You can use the DataSet or the DataReader class to obtain data from a database. DataSet class A DataSet contains a complete representation of data, including the table structure, the relationships between tables, and the ordering of the data. DataSet classes are flexible enough to store any kind of information from a database to an Extensible Markup Language (XML) file. DataSet classes are stateless; that is, you can pass these classes from client to server without tying up server connection resources. The following code demonstrates how to use a DataSet to bind data to a control:
NOTE: You must modify the parameters of the connection string as necessary for your environment.
Visual Basic .NET

Dim cnn As SqlConnection = New SqlConnection(“server=(local);” & _”database=pubs;Integrated Security=SSPI”)Dim cmd As SqlDataAdapter = New SqlDataAdapter(“select * from authors”, cnn)Dim ds As DataSet = New DataSet()cmd.Fill(ds)MyRepeater.DataSource = dsMyRepeater.DataBind() Visual C# .NET

SqlConnection cnn = new SqlConnection(“server=(local);database=pubs;Integrated Security=SSPI”); SqlDataAdapter da = new SqlDataAdapter(“select * from authors”, cnn); DataSet ds = new DataSet(); da.Fill(ds);MyRepeater.DataSource = ds;MyRepeater.DataBind(); Visual J# .NET

SqlConnection cnn = new SqlConnection(“server=(local);database=pubs;Integrated Security=SSPI”); SqlDataAdapter da = new SqlDataAdapter(“select * from authors”, cnn); DataSet ds = new DataSet(); da.Fill(ds); MyRepeater.set_DataSource(ds);MyRepeater.DataBind(); For more information about the DataSet class, see the following .NET Framework SDK documentation:
DataSet Class
http://msdn2.microsoft.com/en-us/library/system.data.dataset(vs.71).aspx(http://msdn2.microsoft.com/en-us/library/system.data.dataset(vs.71).aspx)DataReader class Conversely, if you only need to display (and not change) the data that is to be rendered, a DataReader class may be a better solution. For example, it is better to use a DataReader for a DropDownList control because the DataReader is a forward-only data cursor. The following code demonstrates how to use a SqlDataReader class to bind data to a control:
Visual Basic .NET

Dim cnn As SqlConnection = New SqlConnection(“server=(local);” & _”database=pubs;Integrated Security=SSPI”)Dim cmd As SqlCommand = New SqlCommand(“select * from authors”, cnn)cnn.Open()MyRepeater.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)MyRepeater.DataBind() Visual C# .NET

SqlConnection cnn = new SqlConnection(“server=(local);database=pubs;Integrated Security=SSPI”);SqlCommand cmd = new SqlCommand(“select * from authors”, cnn);cnn.Open();MyRepeater.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);MyRepeater.DataBind(); Visual J# .NET

SqlConnection cnn = new SqlConnection(“server=(local);database=pubs;Integrated Security=SSPI”); SqlCommand cmd = new SqlCommand(“select * from authors”, cnn); cnn.Open();MyRepeater.set_DataSource(cmd.ExecuteReader(CommandBehavior.CloseConnection));MyRepeater.DataBind(); For more information about the SqlDataReader class and data access with ASP.NET, see the following topics in the .NET Framework SDK documentation:
SqlDataReader Class
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx(http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx)
Developing High-Performance ASP.NET Applications
http://msdn2.microsoft.com/en-us/library/5dws599a(vs.71).aspx(http://msdn2.microsoft.com/en-us/library/5dws599a(vs.71).aspx)
Binding in list control templates You can use templates in the list controls to bind and to customize individual records of a data source. This section includes three methods to do this. DataBinder.Eval method When the data source works with data that is returned from a database, the data source may contain numerous pieces of information. You can use the generic DataBinder.Eval method to return data. In the following code sample, the “au_id” field is returned from the data source of the container object:

<%# DataBinder.Eval(Container.DataItem,”au_id”) %> For more information about the DataBinder.Eval method, see the following .NET Framework SDK documentation:
DataBinder.Eval Method
http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx(http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx)Explicit casting If you need more control, use explicit casting. An explicit conversion uses a type conversion keyword. These keywords act as functions, but the compiler generates the code inline. Therefore, execution is slightly faster than with a function call. The following code samples use explicit casting:
Visual Basic .NET

‘ DataTable as the DataSource<%# CType(Container.DataItem, System.Data.DataRowView)(“au_id”) %>’ DataReader as the DataSource<%# CType(Container.DataItem, System.Data.Common.DbDataRecord)(“au_id”) %>’ DataReader as the DataSource<%# CType(Container.DataItem, System.Data.Common.DbDataRecord)(0) %> Visual C# .NET

// DataTable as the DataSource<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %> // DataReader as the DataSource<%# ((System.Data.Common.DbDataRecord)Container.DataItem)["au_id"] %>// DataReader as the DataSource<%# ((System.Data.Common.DbDataRecord)Container.DataItem)[0] %> Visual J# .NET

// DataTable as the DataSource<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %> // DataReader as the DataSource<%# ((System.Data.Common.DbDataRecord)Container.DataItem)["au_id"] %>// DataReader as the DataSource<%# ((System.Data.Common.DbDataRecord)Container.DataItem)[0] %> Note that the preceding samples use either a DataTable, which is a subset of a DataSet, or DataReader as a data source. ItemDataBound event You can also use the ItemDataBound event of the control to bind the data. This event occurs when an item is data bound to the control. The following HTML code sample defines a Repeater control with an ItemTemplate:

<asp:repeater id=rptr runat=server><itemtemplate><asp:label id=lblAuthorID runat=server /></itemtemplate></asp:repeater> The following methods are required in your page:
Visual Basic .NET

public Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)’TODO: Retrieve data from a database,’and bind the data to a list control.End Subpublic Sub rptr_OnItemDataBound(ByVal sender As Object, _ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptr.ItemDataBoundDim rec As DataRowViewrec = e.Item.DataItem’Make sure that you have the data.If Not IsDBNull(rec) ThenDim l1 As Labell1 = e.Item.FindControl(“lblAuthorID”)l1.Text = rec(“au_id”).ToString()End IfEnd Sub Visual C# .NET

public void Page_Init(object sender, System.EventArgs e){rptr.ItemDataBound += new RepeaterItemEventHandler(rptr_OnItemDataBound);}public void Page_Load(object sender, System.EventArgs e){// TODO: Retrieve data from a database,// and bind the data to a list control.}public void rptr_OnItemDataBound(object sender, RepeaterItemEventArgs e){System.Data.Common.DbDataRecord rec = (System.Data.Common.DbDataRecord)e.Item.DataItem;if(rec!=null) //Make sure that you have the data.{Label l1 = (Label)e.Item.FindControl(“lblAuthorID”);l1.Text = rec["au_id"].ToString();}} Visual J# .NET

public void Page_Init(Object sender, System.EventArgs e){rptr.add_ItemDataBound(new RepeaterItemEventHandler(rptr_OnItemDataBound));}private void Page_Load(Object sender, System.EventArgs e){// TODO: Retrieve data from a database,// and bind the data to a list control.}public void rptr_OnItemDataBound(Object sender, RepeaterItemEventArgs e){System.Data.Common.DbDataRecord rec = (System.Data.Common.DbDataRecord)e.get_Item().get_DataItem();if (rec != null) //Make sure that you have the data.{Label l1 = (Label)e.get_Item().FindControl(“lblAuthorID”);l1.set_Text(((rec.get_Item(“au_id”)).ToString()));}}

PRB: Jet Doesn’t Support QueryDefs on a Non-Attached ODBC Table

Symptoms
Jet does not support named QueryDefs on a non-attached ODBC database. A nonattached ODBC database is one that is opened directly with theOpenDatabase method of the WorkSpace object without the use of an .mdb file.
Resolution
The preferred method for opening an external ODBC table is to attach it toan .mdb file. For additional information, please see the followingarticle(s) in the Microsoft Knowledge Base:
150716?(http://support.microsoft.com/kb/150716/EN-US/): DAO: How To Attach to and Create QueryDefs on ODBC Tables
If this method is not appropriate for your application, the followingexample shows how to createQuerydefs with no name:

Set qd = db.CreateQueryDef(“”)qd.SQL = “Select * from authors”

PRB: Jet 4.0 Row-Level Locking Is Not Available with DAO 3.60

Symptoms
According to Microsoft Knowledge Base article 275561?(http://support.microsoft.com/kb/275561/EN-US/) “ACC2000: New Features in Microsoft Jet 4.0″:
To minimize the impact of the increased page size and respond to a long-standing request from developers building applications based on the Microsoft Jet database engine, row-level locking was added to Jet 4.0.However, row-level locking of an Access database is not available with Data Access Objects (DAO) 3.60.
Resolution
To resolve this problem, use ActiveX Data Objects (ADO) to enable row-level locking on an Access database, and then open DAO connections to the database. All subsequent attempts to open DAO connections to the database will respect the locking mode that you set.

CnPool.exe Test Connection Pooling with Tempdb Objects

Symptoms
CnPool.exe contains a sample Visual Basic project that is used to demonstrate how Connection Pooling and Prepared Statements affect the scope and duration of temporary objects within Tempdb. This sample project might be useful in understanding the scope and longevity of temporary objects with Connection Pooling and/or Prepared Statements enabled.
When connection pooling is enabled, any temporary objects that the client creates will remain until the ODBC driver deletes them or the connection is closed, and SQL Server resets all connection specific state variables.
Any temporary object a component creates in SQL Server belongs to the connection, not the component. Consequently, when the component terminates, connection pooling disconnects from SQL Server but does not close the connection. The connection remains in the connection pool and is issued to the next component as needed. Because the connection is not released, the state information is preserved and the temporary objects are visible to the next component using the connection. For example, if you create a temporary table with a component and then terminate the component, when the next component using the same pooled connection attempts to create a temporary table with the same name, the attempt fails because the temporary table already exists for that scope.
This behavior is by design.
Resolution
The following file is available for download from the Microsoft Download Center:
Cnpool.exe(http://download.microsoft.com/download/sql65ent/sample/1/w9xnt4/en-us/cnpool.exe)
Release Date: JUN-10-1998
For additional information about how to download Microsoft Support files, click the following article number to view the article in the Microsoft Knowledge Base:
119591?(http://support.microsoft.com/kb/119591/EN-US/) How To Obtain Microsoft Support Files from Online Services Microsoft scanned this file for viruses. Microsoft used the most current virus-detection software that was available on the date that the file was posted. The file is stored on security-enhanced servers that help to prevent any unauthorized changes to the file.
How to Run the Sample Application Before running the sample application you must register ODBCw32.dll using the Regsvr32.exe utility. To do this, click Run on the Start menu. When the Run dialog box appears, type the following command and click OK:

regsvr32 <path to odbcw32.dll>\odbcw32.dll To examine Connection Pooling in more detail, open the code sample project in Visual Basic design mode. If you get an error when you attempt to run the Visual Basic project in design mode, reselect the reference to ODBCw32.dll (Project-References).
NOTE: The code sample depends on the Pubs database by default. Make the appropriate changes in the connection string for your specific environment.
Before running the Visual Basic application, run the SQL Client utility ISQL/w. In ISQL/w, change the database to Tempdb and type the following in the query command window:

sp_who2select * from sysobjects order by name
Enable Connection Pooling and Disable Prepared Statements Now you are ready to run the code sample.
Select the Enabled option in the Connection Pooling pane.Select the Disabled option button in the Prepared Stmt pane.In the Command text box, type a statement to create a temporary table. For example, type the following:

SELECT * INTO #temp FROM Employee Execute the query text in the ISQL/w query window. Notice that NO connection labeled “ODBC ConnPool” is listed.In the Visual Basic sample application, click Open Connection and then click Execute Command.Rerun the query in the ISQL/w query window. You should now see one connection labeled “ODBC ConnPool” and a #temp table in the listing below.In Visual Basic, click Close Connection and rerun the ISQL/w query. You should see that the “ODBC ConnPool” connection did not disappear and the #temp table is still listed below. This is because Connection Pooling is enabled and although the connection was closed with Visual Basic, it remains active in the Connection Pool until Visual Basic is closed.
Disable Connection Pooling and Disable Prepared StatementsClose Visual Basic and reopen it with the same sample application as in the previous procedure.Run the Visual Basic sample application and this time do not click Enabled in the Connection Pooling pane. Also, make sure that the Disabled option is selected in the Prepared Stmt pane.Type “SELECT * INTO #temp FROM Employee” (without the quotation marks) in the Command text box.Rerun the query in the ISQL/w window and notice that there is no ODBC ConnPool connection listed and the #temp table is not listed below.In Visual Basic, click Open Connection and then click Execute Command.Rerun the ISQL/w query. You will notice that the ODBC ConnPool connection is listed and the #temp table is listed below.In Visual Basic, click Close Connection and rerun the ISQL/w query. You will notice that the ODBC ConnPool connection and the #temp table are gone. This demonstrates that no connections have been pooled and when you close the connection, they are actually closed.
Enable Connection Pooling and Enable Prepared StatementsClose Visual Basic and reopen the sample application.Enable both Connection Pooling and Prepared Stmt and then run the previous statement (SELECT * INTO #temp FROM Employee) by clicking Open Connection and then clicking Execute Command.Before clicking Close Connection in Visual Basic, rerun the ISQL/w query and you will notice that the ODBC ConnPool connection exists (as before), but a temporary stored procedure, #odbc#____xxxx, is listed below. This is because the statement executed was actually wrapped in a stored procedure which was created in the Tempdb and executed.In Visual Basic, click Close Connection and rerun the ISLQ_w query. Notice that the ODBC ConnPool connection remains but the #odbc# reference is gone, unlike the #temp table earlier.
Because we use a prepared statement, the #temp table is created within the scope of a stored procedure and, though Connection Pooling is enabled, the stored procedure goes out of scope and is dropped when the connection is closed in Visual Basic. Because the #temp table created by the stored procedure only exists within the scope and duration of the stored procedure, it is also dropped. For additional information, please see the following article in the Microsoft Knowledge Base:
151536?(http://support.microsoft.com/kb/151536/EN-US/) INF: SQLPrepare and Temporary Stored Procedures in SQL Server You can repeat the previous steps and experiment with different combinations of Connection Pooling and Prepared Statements. If you first execute the statement as a prepared statement and then you open a new connection (without closing the original connection) and execute the statement as a non-prepared statement, another connection is created. The #odbc# object disappears but the #temp object does not.
Conclusion In conclusion, you can avoid some overlapping in the Tempdb that occurs during the creation of temporary tables and other state variables when Connection Pooling is enabled, if you execute the statements within a stored procedure or if you execute prepared statements, for example, ADO - Command.Prepared = True. You can trap the error in code when you attempt to create the temporary table as a prepared statement if you open a new connection (without closing the current connection) and execute the statement. Note that another connection is opened and the connection that caused the temporary object conflict is out of scope for this connection, and the statement should execute normally. Otherwise, you can wait for the default connection timeout of 60 seconds and try again.
Experiment with Connection Pooling with the sample application to gain a better understanding of how Connection Pooling affects the Tempdb environment and how you can avoid overlapping results.