Custom DropDownList not binding evals and bind when inside a gridview template field

Hey folks, I have created a custom server contorl that extends a DropDownList.  However, if for instance I place it inside an EditItemTemplate of a GridView and try putting:

DataValueField='<%# Eval("CategoryID") %>

 

..or the bind, it doesn't actually bind.  Any idea how to make that happen?  I have included my complete code of the control here.  Very useful control for anyone as well!

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient

<DefaultProperty("DataTable"), ToolboxData("<{0}:DataDropDownList runat=server></{0}:DataDropDownList>")> _
Public Class DataDropDownList
    Inherits DropDownList

    Private mstrConnect As String = ""
    Private mstrDataTable As String = ""
    Private mstrFirstItemText As String = "NOT_DEFINED"
    Private mstrStoredProc As String = ""
    Private mstrAutoBind As Boolean = False
    Private mstrFilterText As String = ""
    Private mstrParamName As String = ""
    Private mstrParamValue As String = ""

    ''' <summary>
    ''' Gets or sets the connection string.
    ''' </summary>
    ''' <value>The connection string.</value>
    <Bindable(True), Category("Data"), DefaultValue("")> _
    Public Property ConnectionString() As String
        Get
            Return mstrConnect
        End Get

        Set(ByVal Value As String)
            mstrConnect = Value.Trim
        End Set
    End Property

    ''' <summary>
    ''' Gets or sets the data table that will be used to populate this
    ''' DataDropDownList. Either this or <see cref="StoredProc">StoredProc</see>
    ''' must be set.
    ''' </summary>
    ''' <value>The data table used to populate this DataDropDownList.</value>
    <Bindable(True), Category("Data"), DefaultValue("")> _
    Public Property DataTable() As String
        Get
            Return mstrDataTable
        End Get
        Set(ByVal Value As String)
            mstrDataTable = Value.Trim
        End Set
    End Property

    ''' <summary>
    ''' Gets or sets the stored procedure that will be used to populate this
    ''' DataDropDownList.  Either this or <see cref="DataTable">DataTable</see>
    ''' must be set.
    ''' </summary>
    ''' <value>The stored proc.</value>
    <Bindable(True), Category("Data"), DefaultValue("")> _
    Public Property StoredProc() As String
        Get
            Return mstrStoredProc
        End Get
        Set(ByVal value As String)
            mstrStoredProc = value.ToString
        End Set
    End Property

    ''' <summary>
    ''' If set, AppendDataBindItems is automatically set to false when DataBind
    ''' is called and the value of this property is prepended to this DataDropDownList's items
    ''' and contains a value of "" so that RequiredFieldValidators still function.  A common
    ''' example of its usage is to add "-- Please Select --" (or something similar) as the
    ''' first item in the list but not allow it to be selected when submitting the form.
    ''' Setting this property to the desired display text will accomplish that.
    ''' </summary>
    ''' <value>The text that will be displayed when rendered to the output.</value>
    <Bindable(True), Category("Data"), DefaultValue("")> _
    Public Property FirstItemText() As String
        Get
            Return mstrFirstItemText
        End Get
        Set(ByVal value As String)
            mstrFirstItemText = value
        End Set
    End Property

    ''' <summary>
    ''' If set to True (the default value), DataBind will automatically get called on
    ''' Load.  Otherwise, DataBind will manually need to get called.
    ''' </summary>
    ''' <value><c>true</c> if [auto bind]; otherwise, <c>false</c>.</value>
    <Bindable(True), Category("Data"), DefaultValue("False")> _
    Public Property AutoBind() As Boolean
        Get
            Return mstrAutoBind
        End Get
        Set(ByVal value As Boolean)
            mstrAutoBind = value
        End Set
    End Property

    ''' <summary>
    ''' Gets or sets the filter text that will be used in the where clause of the databinding select.
    ''' This param may only be set if DataTable is defined or an error will be thrown.
    ''' </summary>
    ''' <value>The filter text (the text of the SQL Where clause).</value>
    Public Property FilterText() As String
        Get
            Return mstrFilterText
        End Get
        Set(ByVal value As String)
            mstrFilterText = value
        End Set
    End Property

    ''' <summary>
    ''' Gets or sets the value of the param that will be passed to the value defined in StoredProc.
    ''' Note that if the stored procedure requires more than one parameter, SQL Server will throw
    ''' an error.  If it contains no parameters and this is defined, it will also throw an error.
    ''' If the stored procedure contains exactly one parameter, then the value of this property
    ''' will be used as the parameter's value in conjunction with ParamName.  This param may only
    ''' be set if StoredProc is defined or an error will be thrown.  If this value is set, then
    ''' ParamName must also be set or an error will be thrown.
    ''' </summary>
    ''' <value>The value that will be passed to the stored procedure's parameter.</value>
    Public Property ParamValue() As String
        Get
            Return mstrParamValue
        End Get
        Set(ByVal value As String)
            mstrParamValue = value
        End Set
    End Property

    ''' <summary>
    ''' Gets or sets the name of the param that will be passed to the value defined in StoredProc.
    ''' Note that if the stored procedure requires more than one required parameter, SQL Server
    ''' will throw an error.  If it contains no parameters and this is defined, it will also throw
    ''' an error. If the stored procedure contains exactly one parameter, then this will be used
    ''' in conjunction with ParamValue to pass the value to the parameter.  This param may only be
    ''' set if StoredProc is defined or an error will be thrown.  If this value is set, then
    ''' ParamValue must also be set or an error will be thrown.
    ''' </summary>
    ''' <value>The name that will be passed to the stored procedure's parameter.</value>
    Public Property ParamName() As String
        Get
            Return mstrParamName
        End Get
        Set(ByVal value As String)
            mstrParamName = value
        End Set
    End Property

    Public Overrides Sub DataBind()
        Dim strSQL As String
        Dim intSelectedIndex As Integer

        Try
            Check()

            ' Build SQL String
            If Not String.IsNullOrEmpty(mstrStoredProc) Then
                strSQL = mstrStoredProc
            Else
                strSQL = String.Format("SELECT DISTINCT {0}, {1} FROM {2}", _
                 MyBase.DataTextField, MyBase.DataValueField, _
                 mstrDataTable)

                If Not String.IsNullOrEmpty(mstrFilterText) Then
                    strSQL &= " WHERE " & mstrFilterText
                End If
            End If
           
            ' Fill in DataSource
            MyBase.DataSource = _
             Me.GetDataSet(strSQL, mstrConnect)

            ' Bind the Data
            intSelectedIndex = IIf(MyBase.SelectedIndex = -1, 0, MyBase.SelectedIndex)
            MyBase.AppendDataBoundItems = False
            MyBase.DataBind()
            If mstrFirstItemText <> "NOT_DEFINED" Then
                MyBase.Items.Insert(0, New ListItem(mstrFirstItemText, ""))
            End If

            If MyBase.Items.Count >= intSelectedIndex + 1 Then
                MyBase.SelectedIndex = intSelectedIndex
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Private Function GetDataSet(ByVal SQL As String, _
    ByVal ConnectString As String) As DataSet
        Dim ds As New DataSet
        Dim da As SqlDataAdapter

        Try
            If String.IsNullOrEmpty(mstrStoredProc) Then
                da = New SqlDataAdapter(SQL, ConnectString)
            Else
                Dim cmd As New SqlCommand
                cmd.Connection = New SqlConnection(ConnectString)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = SQL
                If Not String.IsNullOrEmpty(mstrParamValue) Then
                    cmd.Parameters.AddWithValue(mstrParamName, mstrParamValue)
                End If
                da = New SqlDataAdapter
                da.SelectCommand = cmd
            End If

            da.Fill(ds)
            Return ds
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Sub Check()
        Dim strProp As String = ""

        ' Check to see if all values
        ' are filled in correctly
        If String.IsNullOrEmpty(DataTextField) Then
            strProp &= "DataTextField"
        End If

        If String.IsNullOrEmpty(DataValueField) Then
            If strProp <> "" Then
                strProp &= ", "
            End If
            strProp &= "DataValueField"
        End If

        If String.IsNullOrEmpty(mstrConnect.Trim()) Then
            If strProp <> "" Then
                strProp &= ", "
            End If
            strProp &= "ConnectString"
        End If


        If ((Not String.IsNullOrEmpty(mstrParamName)) OrElse (Not String.IsNullOrEmpty(mstrParamValue))) AndAlso (Not String.IsNullOrEmpty(mstrFilterText)) Then
            If strProp <> "" Then
                strProp &= ", "
            End If
            strProp &= "Both FilterText and ParamName/ParamValue cannot be set.  Please use ParamName/ParamValue for StoredProc and FilterText for DataTable"
        End If

        If String.IsNullOrEmpty(mstrStoredProc) Then
            If Not String.IsNullOrEmpty(mstrParamName) Then
                If strProp <> "" Then
                    strProp &= ", "
                End If
                strProp &= "ParamName cannot be defined if StoredProc is not used"
            End If

            If Not String.IsNullOrEmpty(mstrParamValue) Then
                If strProp <> "" Then
                    strProp &= ", "
                End If
                strProp &= "ParamValue cannot be defined if StoredProc is not used"
            End If

            If String.IsNullOrEmpty(mstrDataTable) Then
                If strProp <> "" Then
                    strProp &= ", "
                End If
                strProp &= "DataTable or StoredProc"
            End If
        Else
            If Not String.IsNullOrEmpty(mstrFilterText) Then
                If strProp <> "" Then
                    strProp &= ", "
                End If
                strProp &= "FilterText cannot be defined if DataTable is not set"
            End If

            If Not String.IsNullOrEmpty(mstrDataTable) Then
                If strProp <> "" Then
                    strProp &= ", "
                End If
                strProp &= "Both DataTable and StoredProc cannot be declared - please use one or the other"
            End If

            If ((Not String.IsNullOrEmpty(mstrParamName)) AndAlso (String.IsNullOrEmpty(mstrParamValue))) OrElse _
            ((Not String.IsNullOrEmpty(mstrParamValue)) AndAlso (String.IsNullOrEmpty(mstrParamName))) Then
                If strProp <> "" Then
                    strProp &= ", "
                End If
                strProp &= "If either ParamName or ParamValue are defined, both must be set"
            End If
        End If
       
        If strProp <> "" Then
            strProp = "These properties are required for DataDropDownList: " _
             & strProp
            Throw New ApplicationException(strProp)
        End If
    End Sub

    Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
        MyBase.RenderContents(output)
    End Sub

    Private Sub DataDropDownList_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If mstrAutoBind Then
            Me.DataBind()
        End If
    End Sub

    Private Sub DataDropDownList_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
End Class
 

0
ahillyer
4/27/2009 5:49:38 PM
asp.net.custom-server-controls 3498 articles. 0 followers. Follow

2 Replies
842 Views

Similar Articles

[PageSpeed] 30

Please try using

DataValueField="CategoryID"
0
RemithR
4/27/2009 6:12:59 PM
I'm not sure what I was thinking (brain fart?) but that was it.  Thanks.

-Aaron
0
ahillyer
4/29/2009 3:42:56 PM
Reply:

Similar Artilces:

Gridview: Custom binding to Template Field controls
I have a grid view that displays address data, and I need to do some custom databinding to controls in the ItemTemplate.  In this case, rather than showing 2 character state code, I need to perform a lookup and present the user with the full state name.  The only problem is, during the RowCreated event I cannot figure out how to access the text box inside the item template.  The datagrid layout looks something like this, I'm free typing it and it's abbreviated so excuse the incompleteness:   <asp:Gridview ID="GridView1" runat="server"...

How to add a Web server or HTML server controls (such as CheckBox) to the template in GridView and bind the controls to a data source.
How to add a Web server or HTML server controls (such as CheckBox) to the template in GridView and bind the controls to a data source. Normally, We can add a Web server or HTML server controls to the template in GridView control,just like the Code 1I hope to do the same thing by programming (just like the Code 2), but I can ony add the BoundField,I don't know how to add a CheckBox control to the template in GridView , could you help me? //--------------------------------------------Code 1------------------------------------------------------------<asp:GridView AutoGenerateColumns="False...

Custom Templated Control, Nested Controls and Data Binding
Good day,  I have a Custom Templated Control for which the CreateChildControl method is called 3 times during the page request (and it is not a PostBack). I don't understand why it is so and how I can improve that to a single call, so I am turning to the forums. Here is the structure in which the control is used (in abreviated form):  <asp:formview><asp:repeater><mycustomtemplatedcontrol templatediscriminator=""'<#% Eval("SomeProperties") %>'> <template1><# Eval("Prop1")%></template1&g...

Control Custom Bindings with the GridView
Hi!Im currently dealing with a binding problems. My requirement is to bound my controls (DropDownList, TextBoxes) to some particular columns of the GridView. Like when user select the row from the grid view then its columns values should be displayed in dropdowns and textboxes.Also is there anyway that i can bind these controls with the gridview or is that possible to do it client side as all the data is loaded in the gridview then just for displaying we need to go server side.Kindly suggest some suitable solution.Thanks! RegardsMohsin Shahzad  Also whats the preferred way of doi...

Usercontrol vs Custom Server Controls, Any need for Custom Server Controls
Hello I'm new to ASP.Net so this is probably a stupid question but, is there any need to create customer server controls now that you can pre-compile usercontrols into a dll and thus easily share between applications? This blog post from David Ebb describes how to do it and the restrictions he note don't seem that bad (other than being able to embed resources such as images in the dll). http://blogs.msdn.com/davidebb/archive/2005/10/30/487160.aspx His article desribes the techniques for ASP.Net 2.0 and he suggests that there will be further improvements in .Net 3.5 in this ar...

Can't find a GridView inside a template of a custom templated web control
This is my first Templated Web Control I've written and I hope someone can help. I have three templates inside my web control and I'm trying to find a GridView inside one of them.  Naturally, it's throwing a null reference exception.  Here is the code for my user control:  1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Text; 5 using System.Web; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 9 namespace MyWebControls 10 { 11 [ToolboxData("&lt;{0}:Sec...

Custom Template Fields in Gridview Control
I have a gridview and have read several "How-To's" on creating a Custom Template Field, but am having a problem trying to get my specific situation to operate correctly. The code behind my custom template class is as follows:  Public Class clsCustomGridViewTemplate Implements ITemplatePrivate m_colType As ListItemType Private m_sColumnName As StringPublic Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn Try Select Case m_colType Case ListItemType.AlternatingItemCase ListItemType.EditItem Case L...

Custom class binding to GridView control
I have a collection of classes, that includes types from other classes. When I bind that collection to GridView, it only bind the memebers that are not from other classes.For example if you look at one member of the collection    public class BLOrdering    {        public BLOrder _myOrder;        public int _numberOfItems        public double _deliveryTime;     } numberOfItems and deliveryTime show up in the GridView but not the BLOrder my...

problems listenening to events on a custom server control from another custom server control
 Hi all,I am having problems listening to events on one of custom server controls(AddBookmark) from another custom server control(BookmarkList). The listener or the BookmarkList control has a property that can be set to the AddBookmark control (string at design but the reference is obtained at run-time). I am able to get a reference to the AddBookmark control and add a listener to it on the BookmarkList control on the OnPrender of BookmarkList. But the problem is that when the events on AddBookmark gets fired, the listener added from the BookmarkList is no longer present and the listene...

Custom Server Control Vs Web Parts, Any need for Custom Server Control
Hello I've just posted a similar question on why you need server controls when you can pre-compile usercontrols and redistribute them. http://forums.asp.net/p/1397433/3010100.aspx#3010100 I've seen lots of (usercontrol vs web part) but not much on web part vs custom server control. According to the MSDN site you can put web parts onto a normal asp.net page outside of a web part zone and they behave just like custom server controls. So, if you are creating a bunch of controls for redistribution to customer asp.net sites and/or SharePoint sites why don't you just create Web Par...

Custom controls called from inside other custom controls???
I'm fairly new to writing controls in ASP.NET so, forgive the I am trying to create a base page class which will call 3 custom controls. This base page class will span across multiple projects hence the reason I am not creating user controls. These 3 custom controls are: 1. TopNav-uses render method to display an HTML table with graphics for top navigation. 2. ImagePairs-uses prerender method to add javascript code to manage what graphic is displayed in TopNav onMouseOver and onMouseOut 3. MgrHeader-uses render method to display an HTML table with s...

Creating Custom Controls With Custom Controls Inside Of Them
Hello, I am trying to create a custom control for creating tabs. The idea is that our designer can just use the control tags to generate the tabs.  The problem that I am running into is that I want to be able to have a custom control that allows any number of child custom controls. So there would be a TabContainer Control, and within that there would be any number of tabs.  The idea is similar to how an asp:DropDown list can have any number of ListItems within them.  Here is my code, any help is appreciated. 1 <!-- TAB CONTAINER -->2 <%@ Control Language=&...

Custom Server Control Made of Custom Controls?
I'm giving myself a crash course in custom server controls, and I have a quick general question. Can I have a custom server control that is composed of other server controls I created. I'm pretty sure the answer is yes, but I want to be positive. Yes http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondevelopingcompositecontrols.asp Shows how to combine existing controls into a new control using class composition. -ron Thanks! ASP.NET so rocks! Making page components extensible objects is such a great idea! I love it....

Binding data to GridView Control Using Custom Script
I am having a problem populating a gridview using a custom sql script.  The following is my asp code: <body> <form id="form1" runat="server"> <div> <table id="container"> <tr> <td colspan="4"> <asp:Image ID="Image1" runat="server" Height="78px" ImageUrl="~/images/mohmsban.png" /> </td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td> <asp:LoginN...

Web resources about - Custom DropDownList not binding evals and bind when inside a gridview template field - asp.net.custom-server-controls

Tag Synonyms - Stack Overflow
Q&A for professional and enthusiast programmers

Accidental entities - what about the UI?
This post is a follow-up to my previous blog post " Accidental entities - you don't need that identity ". In that post, we followed a consultant ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Air Astana - Join Now
Thank you for considering membership of Nomad Club – Kazakhstan’s first Frequent Flyer Program. You could soon be on your way to earning free ...

Languages -> C# Articles, Tutorials, Examples: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Blog - Avisra
Avisra Web Development Home Blog Services Contact The Blog Latest Module Builder: How can we make it better? Sitefinity by Chris on July 2, 2013 ...

Online Booking Tool Support
This Online Booking Tool Support page might help you as you navigate through the process of booking travel through your OBT provided by CWT. ...

@Html and beyond
... ); } return string .Format( “{0}{1}” , me.Member.Name, id); } The Html building methods are quite simple. Building a dropdownlist for a ...

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Unit Testing DateTime.Now Without Isolation
public virtual void SeedWithYearsSince(DropDownList list, int year){ for (int index = year; index

Resources last updated: 11/21/2015 6:51:54 AM