Link to home
Start Free TrialLog in
Avatar of shelbyinfotech
shelbyinfotech

asked on

How to use OnItemDataBound to disable a drop down box at run time on Datagrid 1.1

How can i disable/enable an item in a datagrid using the OnItemDataBound method ?
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

You can use FindControl from the DataGridItem to get a reference to the DropDownList embedded in the DataGrid, and then set Enabled = True/False.

Bob
Was putting this example together when Bob posted...but it's basically what he describes.
aspx:
    <form id="form1" runat="server">
        <div>
            <asp:DataGrid ID="Datagrid1" runat="server" AutoGenerateColumns="true">
                <Columns>
                    <asp:TemplateColumn>
                        <ItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server">
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                </Columns>
            </asp:DataGrid>
        </div>
    </form>
 
codebehind:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            'fake data to give some rows
            Dim dt As New DataTable
            Dim col As New DataColumn("MyColumn")
            dt.Columns.Add(col)
            For i As Integer = 0 To 9
                Dim r As DataRow
                r = dt.NewRow
                r.Item("MyColumn") = i
                dt.Rows.Add(r)
            Next
            'bind to datagrid
            With Me.Datagrid1
                .DataSource = dt
                .DataBind()
            End With
        End If
    End Sub
 
    Private Sub Datagrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles Datagrid1.ItemDataBound
        'make sure we're in the grid, not header/footer
        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            'disable all:
            ''DirectCast(e.Item.FindControl("DropDownList1"), DropDownList).Enabled = False
 
            'disable based on data criteria:
            If e.Item.DataItem("MyColumn") = "5" Then
                DirectCast(e.Item.FindControl("DropDownList1"), DropDownList).Enabled = False
            End If
        End If
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial