Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1351
  • Last Modified:

Gridview Edit - different edit controls based on Database data result


Hi All,

I'm loving the new gridview! I'm having a problem though populating default values to a drop down list where the values do not come from a database result but from the result of a sub.

What I have is a gridview, and when the user clicks edit, I use the GridView1_RowEditing to set what default data the drop list will have in it using something like:

Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
       
        Dim strSMSDB As String = ConfigurationManager.AppSettings("SMSDBName").ToString
       
        Dim strPropertyName As String = GridView1.DataKeys(e.NewEditIndex)(0)
        iPropertyType = GridView1.DataKeys(e.NewEditIndex)(1)
        Dim strColumnName As String = GridView1.DataKeys(e.NewEditIndex)(2).ToString
        Dim sSQL As String
 
        Select Case iPropertyType

            Case 3
               
               
                sSQL = "SELECT PropertyName AS ID, Value FROM dbo.WD_ADPropertyValues WHERE PropertyName = '" & strPropertyName & "' ORDER BY Value"
         
            Case 5
               
                sSQL = "Select DISTINCT " & strColumnName & " AS ID, " & strColumnName & " AS Value FROM " & strSMSDB & ".dbo.v_R_User WHERE " & strColumnName & " IS NOT NULL ORDER BY " & strColumnName & " ASC"

        End Select

        ESD2.SelectCommand = sSQL

    End Sub

This is all fine.

However, When Case  = 8 I need to get the results from an Active Directory query. I have tried doing:

  Case 8
                Dim ddl As DropDownList = GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore")
                populateExchangeStore(ddl)

 Sub populateExchangeStore(ByVal DropList As DropDownList)
       
        Dim AD As New ActiveDirectory
       
        Dim mysearcher As System.DirectoryServices.DirectorySearcher
        Dim result1 As System.DirectoryServices.SearchResult
       
        mysearcher = AD.GetExchangeStore()
       
        If IsNothing(mysearcher) = False Then
           
            For Each result1 In mysearcher.FindAll
                Dim item As New ListItem
                item.Value = result1.GetDirectoryEntry().Properties("distinguishedName").Value
                item.Text = result1.GetDirectoryEntry().Properties("name").Value
                DropList.Items.Add(item)
            Next
        End If
           
    End Sub

but I get object not set to instance of object. This is because since the drop list is in an template, it does not exist yet?

Please help and fast!

0
mooka
Asked:
mooka
  • 8
  • 7
1 Solution
 
lijunguoCommented:
try this instead
Dim ddl As New DropDownList = Ctype(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)
0
 
mookaAuthor Commented:

Thanks for responding. The statement provided is giving an error. When I try:

 Dim ddl As DropDownList = CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)

This thows the origional error of Object reference not set to an instance of an object.

 Dim ddl As New DropDownList = CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList) gives end of statement expected.

The control ddlExchangeStore does exist on the page in an edit field. Should I create it in code instead and place the control on the page on edit?

Thanks for your help.
0
 
lijunguoCommented:
try this again.

Dim ddl As New DropDownList
ddl =  CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
mookaAuthor Commented:
Thanks again for responding.

That still thew System.NullReferenceException: Object reference not set to an instance of an object.

The line:

Dim ddl As New DropDownList
ddl =  CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)

executes ok. My next step is to pass the ddl to a sub as follows for population:

 populateExchangeStore(ddl)

Sub populateExchangeStore(ByVal DropList As DropDownList)
       
        Dim AD As New ActiveDirectory
       
        Dim mysearcher As System.DirectoryServices.DirectorySearcher
        Dim result1 As System.DirectoryServices.SearchResult
       
        mysearcher = AD.GetExchangeStore()
       
        If IsNothing(mysearcher) = False Then
           
            For Each result1 In mysearcher.FindAll
                Dim item As New ListItem
                item.Value = result1.GetDirectoryEntry().Properties("distinguishedName").Value
                item.Text = result1.GetDirectoryEntry().Properties("name").Value
                DropList.Items.Add(item) <-------- Errors on this line
            Next
        End If
       
       
    End Sub
0
 
mookaAuthor Commented:
Quick update,

Everything works fine if I move the droplist outside of the EditItemTemplate and locate the control using:

 ddl = CType(Page.FindControl("ddlExchangeStore"), DropDownList)
               

I'm using this in the GridView1_RowEditing routine. Should it be somewhere else? It seems like the right place though. Perhaps the control is not yet created? Do you know which routine would fire right after the control is rendered?

Thanks,

John
0
 
lijunguoCommented:
change this
Sub populateExchangeStore(ByVal DropList As DropDownList)
to
Sub populateExchangeStore(ByRef DropList As DropDownList)
0
 
mookaAuthor Commented:
Same deal as before:

System.NullReferenceException: Object reference not set to an instance of an object.


 Sub populateExchangeStore(ByRef DropList As DropDownList)
       
        Dim AD As New ActiveDirectory
       
        Dim mysearcher As System.DirectoryServices.DirectorySearcher
        Dim result1 As System.DirectoryServices.SearchResult
       
        mysearcher = AD.GetExchangeStore()
       
        If IsNothing(mysearcher) = False Then
           
            For Each result1 In mysearcher.FindAll
                Dim item As New ListItem
                item.Value = result1.GetDirectoryEntry().Properties("distinguishedName").Value
                item.Text = result1.GetDirectoryEntry().Properties("name").Value
                DropList.Items.Add(item)   <-------- Error
            Next
        End If
       
       
    End Sub
 
0
 
lijunguoCommented:
can you find the control now? And which line causes the error?
DropList.Items.Add(item)   <-------- Error
Is above line?
0
 
mookaAuthor Commented:


The control still can't be found. I'm taking the sub out of play and still get the error:

   
Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)

Dim ddl As New DropDownList
ddl =  CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)
ddl.visible = true    <-------- Error System.NullReferenceException: Object reference not set to an instance of an object.

End Sub


.... html

  <asp:TemplateField HeaderText="Property Value" SortExpression="Value">
                    <EditItemTemplate>
 <asp:DropDownList ID="ddlExchangeStore" runat="server">
                      </asp:DropDownList>
                    </EditItemTemplate>
    </asp:TemplateField>


Please someone help!!!
0
 
lijunguoCommented:
Really don't know why you cannot find the control. There is something wrong with your code. Here is a very simple Gridview, you could test it.

testGrid.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="testGrid.aspx.vb" Inherits="Members_testGrid" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" HorizontalAlign="Center" Width="100%" >
            <Columns>
                <asp:BoundField DataField="column1" HeaderText="col1" />
                <asp:BoundField DataField="column2" HeaderText="col2" />
                <asp:BoundField DataField="column3" HeaderText="col3" />
                <asp:TemplateField HeaderText="ddl">
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlExchangeStore" runat="server">
                        <asp:ListItem>list 1</asp:ListItem>
                        <asp:ListItem>list 2</asp:ListItem>
                        <asp:ListItem>list 3</asp:ListItem>
                        </asp:DropDownList>
                       
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
            <RowStyle HorizontalAlign="Center" />
        </asp:GridView>
   
    </div>
    </form>
</body>
</html>

codebehind file:
Imports System.Data

Partial Class Members_testGrid
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindGridView()

    End Sub
    Sub BindGridView()
        Dim ds As New DataSet
        ds = SampleData()
        GridView1.DataSource = ds.Tables(0).DefaultView

        GridView1.DataBind()

    End Sub

    Private Function SampleData() As DataSet
        Dim ds As DataSet = New DataSet
        Dim dt As DataTable = ds.Tables.Add("SampleData")
        dt.Columns.Add("Column1", GetType(String))
        dt.Columns.Add("Column2", GetType(String))
        dt.Columns.Add("Column3", GetType(String))
        'dt.Columns.Add("Column4", GetType(String))
        'dt.Columns.Add("Column5", GetType(String))
        Dim dr As DataRow
        Dim i As Integer = 1
        While i <= 10
            dr = dt.NewRow
            dr("Column1") = "Cell1:" + i.ToString
            dr("Column2") = "Cell2:" + i.ToString
            dr("Column3") = "Cell3:" + i.ToString
            'dr("Column4") = "Cell4:" + i.ToString
            'dr("Column5") = "Cell5:" + i.ToString
            dt.Rows.Add(dr)
            System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
        End While
        Return ds
    End Function

    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
        GridView1.EditIndex = e.NewEditIndex
        BindGridView()
        Dim ddl As New DropDownList
        ddl = CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)
        ddl.SelectedIndex = 1

    End Sub

    Sub myGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
        GridView1.EditIndex = -1
        BindGridView()
    End Sub


End Class

0
 
mookaAuthor Commented:

Thanks so much for a working example.

The main difference I see is that on the GridView1_RowEditing you have 2 additional commands:

 GridView1.EditIndex = e.NewEditIndex

 BindGridView()

Can you explain please the need for these commands? Why do you have to tell the grid which index is being edited, isnt that already known and why do you have to bind to the grid and repopulate the data again?
0
 
mookaAuthor Commented:


Your example works well when the values of the droplist are static. The key problem seems to be populating the drop list dynamically and not using a dataset.

I have found that id I move the routine to the GridView1_RowDataBound and wrap the routine in a try catch it works ok.



0
 
lijunguoCommented:
Actually you may comment them out and see what happens, you'll understand it.
GridView1.EditIndex = e.NewEditIndex ' for editing a specific row, without it, edit link will not be working.

 BindGridView() 'without this line, you can not find the "ddl" control.

Once you find the "ddl" control, there is no reason you cannot populate dynamicly. First thing, make sure you could find the "ddl" control, then you do the dynamic bind ddl. Without finding the "ddl" , how do you do the logic with "ddl" and test it?

Regards,
Lijunguo

0
 
lijunguoCommented:
a sample
    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
        GridView1.EditIndex = e.NewEditIndex
        BindGridView()
        Dim ddl As New DropDownList
        ddl = CType(GridView1.Rows(e.NewEditIndex).FindControl("ddlExchangeStore"), DropDownList)
        ddl.SelectedIndex = 1
        bindDdl(ddl)
    End Sub

    Sub bindDDL(ByRef ddl As DropDownList)
        Dim i As Integer = 1
        While i <= 10
            Dim item As New ListItem

            item.Text = "item " + i.ToString
            item.Value = i.ToString
            ddl.Items.Add(item)
            i = i + 1
        End While
    End Sub
0
 
mookaAuthor Commented:
Thanks so much for you help. Although I'm still having some problems, I understand it better now.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 8
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now