Link to home
Start Free TrialLog in
Avatar of dash420
dash420Flag for Canada

asked on

Dropdrown in datagrid

I want to put dropdrown in the datagrid to update. as drop drow is not defined always. it will appears onclick of edit command. my problem is that i am unable to set previous value in combo box to selected. only first value getting selected.

my code is like this.

<asp:DataGrid id="dgBookList" Width="600" Runat="server" AllowCustomPaging="False" AutoGenerateColumns="False" PagerStyle-Visible="true" HeaderStyle-CssClass="GRIDTH" AlternatingItemStyle-BackColor="lightgrey" BackColor="white" CellPadding="2" CellSpacing="2" DataKeyField="book_number" PagerStyle-Position="TopAndBottom" PagerStyle-Mode="NumericPages" PagerStyle-HorizontalAlign="Right" OnPageIndexChanged="DG_paged" OnEditCommand="doItemEdit" OnUpdateCommand="doItemUpdate" OnCancelCommand="doItemCancel" GridLines="None">

<asp:TemplateColumn HeaderText="Author Name">
<columns>
        ...
        ... other control
                              <ItemTemplate>
                                   <asp:Label Text='<%#Container.DataItem("user_id")%>' Runat="server" ID="lbluserId">
                                   </asp:Label>
                              </ItemTemplate>
                              <EditItemTemplate>
                                   <asp:DropDownList Runat="server" Id="selUser"
                                DataSource='<%# GetUser(DataBinder.Eval(Container.DataItem, "user_id")) %>'
                                DataValueField="user_id"/>
                              </EditItemTemplate>
                         </asp:TemplateColumn>
                         <asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />

          </Columns>
               </asp:DataGrid>



in codebehind

Function GetUser(ByVal struserId As String)
        Dim strSql As String
        strSql = "SELECT user_id ,user_name FROM users"
        Dim objDa As New SqlDataAdapter(strSql, objConnection)
        Dim objDs As New DataSet()
        objDa.Fill(objDs, "users")
        'If blnflag Then
        selUser.SelectedItem.Value = lbluserId.Text
        'End If
        Return objDs.Tables("users")

    End Function

also if column value is null, it giving error "from type 'DBNull' to type 'String' is not valid."

cna any suggests how to do it.

Avatar of CarlosMu
CarlosMu

Try setting the selected index value of selUser.  I guess that the best option would be to loop thru the values on selUser until the Selected text = lbluserid.Text

dim intMax as integer = selUser.items.count

with selUser
for .SelectedIndex = 0 to (intMax - 1)
   if .SelectedText = lbluserid.Text then
       exit for              ' Found match
   end if
next
You've got the right idea here, but you're trying to set the selected index in the wrong place.

<EditItemTemplate>
                                  <asp:DropDownList Runat="server" Id="selUser"
                               DataSource='<%# GetUser(DataBinder.Eval(Container.DataItem, "user_id")) %>'
                               DataValueField="user_id"/>
                             </EditItemTemplate>

You need to add another property here,

SelectedIndex="
<%# GetSelIndex(Container.DataItem("FieldId")) %>"

Inside your GetSelIndex function (which should return an int), loop through your dataset until you find the current value...

(sorry, this is C#, I don't use VB)

public int GetSelIndex(string FieldId)
{
 DataTable tbl = dataset.Tables["YourTable"];
 for (int i = 0; i < tbl.Rows.Count; i++)
 {
   if (tbl.Rows[i]["FieldId"].ToString() == FieldId)
     return i;
 }
}

For more info, see question

https://www.experts-exchange.com/questions/20509280/DropDownList-within-a-DataGrid.html

Forgot to add....

Get rid of the selUser.SelectedItem code in the GetUser function, you don't need it.

Function GetUser(ByVal struserId As String)
       Dim strSql As String
       strSql = "SELECT user_id ,user_name FROM users"
       Dim objDa As New SqlDataAdapter(strSql, objConnection)
       Dim objDs As New DataSet()
       objDa.Fill(objDs, "users")
       Return objDs.Tables("users")

   End Function
This works for me...

Declare a Global Variable, Like This:

#Region "Public Variable Declarations"
    Public gCurrentType As String
#End Region

Within the Edit Event, capture the value of the current record and store it to the Global variable. In this example, I assume the control is named DropDownList1. Like this:

Public Sub MyDataGrid_Edit(ByVal Sender As Object, ByVal e As DataGridCommandEventArgs)

...

' Capture Current Values for Item to Be Editted
gCurrentType = CType(e.Item.FindControl("DropDownList1"), Label).Text

...

End Sub

Then code for the ItemDataBound event to assign the control's SelectedIndex property. Since I am using the Name value of the control instead of the Value property, I use the FindByText method to get the Index.
           
Public Sub MyDataGrid_ItemDataBound(ByVal s As Object, ByVal e As DataGridItemEventArgs)

' Presets the DropDownLists to the Current Value
If e.Item.ItemType = ListItemType.EditItem Then

' Item Types
Dim myTypeDropDown As DropDownList
myTypeDropDown =
CType(e.Item.FindControl("DropDownList1"), DropDownList)
           
myTypeDropDown.SelectedIndex =
myTypeDropDown.Items.IndexOf(myTypeDropDown.Items.FindByText(gCurrentType))

End If

End Sub

Like I said, this works perfectly for me. If you still have some problems, post again.
Avatar of dash420

ASKER

hi  Frostbyte_Zero
this line gives me problem
' Capture Current Values for Item to Be Editted
gCurrentType = CType(e.Item.FindControl("DropDownList1"), Label).Text

errir is like this

"
  Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

"


Avatar of dash420

ASKER

hi  wiseguy_2112

i tried your method it is also fails. givng error something like uanble to declare runtime property
post your code (just the itemtemplate and you code behind) and we'll try to figure out what the problem is.

Avatar of dash420

ASKER

Hope u can find out the problem

Imports System.Data
Imports System.Data.SqlClient

Public Class editdatagrid
    Inherits System.Web.UI.Page

    Protected WithEvents dgBookList As System.Web.UI.WebControls.DataGrid
    Protected WithEvents selUser As DropDownList
    Protected WithEvents lbluserId As Label
    Protected btnEditColumn As System.Web.UI.WebControls.EditCommandColumn


    Protected blnflag As Boolean = False


    Protected objUtility = New utility()
    Protected WithEvents Table1 As System.Web.UI.WebControls.Table

    Dim objConnection As New SqlConnection(ConfigurationSettings.AppSettings("connString"))

#Region " Web Form Designer Generated Code "

    'Public seluserid As String
    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not IsPostBack Then
            bindGrid()
            'btnEditColumn. .Attributes.Add("onclick", "return fnTest();")
        End If
    End Sub


    Sub bindGrid()
        Dim objDA As SqlDataAdapter
        Dim objDS As DataSet
        Dim strSql As String
        Dim intPageNo As Integer
        Dim intPageSize As Integer
        Dim intRecCount As Integer

        strSql = " SELECT book_number,title_name,author_name,publisher,no_of_copies,user_id FROM book " & "_"
        strSql = strSql & " ORDER BY book_number"

        objDA = New SqlDataAdapter(strSql, objConnection)
        objDS = New DataSet()
        intPageNo = CInt(dgBookList.CurrentPageIndex) + 1
        If blnflag Then
            Response.Write("dkjdj")
            'selUser.SelectedIndex = lbluserId.Text
        End If
        Try
            objDA.Fill(objDS, "book")
            intRecCount = objDS.Tables("book").Rows.Count.ToString()
            dgBookList.PageSize = 10
            intPageSize = CInt(dgBookList.PageSize)
            If intRecCount > 2 Then
                dgBookList.AllowPaging = True
            End If
            dgBookList.DataSource = objDS.Tables("book").DefaultView
            dgBookList.DataBind()
        Catch e As Exception
            dgBookList.CurrentPageIndex = 0
            Response.Write(Err.Description)
        End Try
    End Sub

    Sub DG_paged(ByVal Sender As Object, ByVal E As DataGridPageChangedEventArgs)
        dgBookList.CurrentPageIndex = E.NewPageIndex
        bindGrid()
    End Sub

   

    Sub doItemEdit(ByVal objSource As Object, ByVal objArgs As DataGridCommandEventArgs)

        dgBookList.EditItemIndex = objArgs.Item.ItemIndex
        blnflag = True
        bindGrid()
        'Dim objUserTo = CType(objArgs.Item.FindControl("selUser"), DropDownList)
        'seluserid = CType(objArgs.Item.FindControl("selUser"), Label).Text

        'Dim objDataGrid = CType(objSource, DataGrid)
        'objDataGrid.EditItemIndex = objArgs.Item.ItemIndex


        ' selUser.SelectedIndex = "3" 'selUser.Items.IndexOf(selUser.Items.FindByText("george"))

    End Sub

    Sub doItemCancel(ByVal objSource As Object, ByVal objArgs As DataGridCommandEventArgs)

        dgBookList.EditItemIndex = -1
        'populateUser()

        bindGrid()

    End Sub

    Function GetUser()
        Dim strSql As String
        strSql = "SELECT 1 as mysortval, 'Select' as user_id,'' as user_name FROM users UNION  "
        strSql = strSql & "SELECT 2 as mysortval, user_id ,user_name FROM users"
        Dim objDa As New SqlDataAdapter(strSql, objConnection)
        Dim objDs As New DataSet()
        objDa.Fill(objDs, "users")
        'If blnflag Then
        'selUser.SelectedItem.Value = lbluserId.Text
        'End If
        Return objDs.Tables("users")

    End Function


Sub doItemUpdate(ByVal objSource As Object, ByVal objArgs As DataGridCommandEventArgs)

        Dim objBookTitle = CType(objArgs.Item.FindControl("txtTitle"), TextBox)
        Dim objAuthor = CType(objArgs.Item.FindControl("txtAuthor"), TextBox)
        Dim objPublisher = CType(objArgs.Item.FindControl("txtPublisher"), TextBox)
        Dim objCopies = objArgs.Item.Cells(4).Controls(0)
        'Dim objIssueTo = objArgs.Item.Cells(5).Controls(0)
        Dim objIssueTo = CType(objArgs.Item.FindControl("selUser"), DropDownList)

        Dim strSql As String

        strSql = "UPDATE book set title_name = " & objUtility.QuotedString(objBookTitle.Text) & "," & _
                 "author_name = " & objUtility.QuotedString(objAuthor.Text) & "," & _
                 "publisher = " & objUtility.QuotedString(objPublisher.Text) & "," & _
                 "no_of_copies = " & objCopies.Text & ","
        If objIssueTo.SelectedItem.Text <> "Select" Then
            strSql = strSql & "user_id = " & objUtility.QuotedString(objIssueTo.SelectedItem.Text) & ""
        Else
            strSql = strSql & "user_id = NULL"
        End If
        strSql = strSql & " WHERE book_number = " & dgBookList.DataKeys(objArgs.Item.ItemIndex)

        'Response.Write(strSql)

        Dim objCommand As New SqlCommand(strSql, objConnection)

        Try
            objConnection.Open()
            objCommand.ExecuteNonQuery()
            objConnection.Close()

        Catch Exc As SqlException
            Response.Write("When executing Query" & Exc.Message & "Query : " & strSql)
            Response.End()
        End Try
        dgBookList.EditItemIndex = -1
        'populateUser()
        bindGrid()

    End Sub

    'Public Sub dgBookList_ItemDataBound(ByVal s As Object, ByVal e As DataGridItemEventArgs)

    '    ' Presets the DropDownLists to the Current Value
    '    If e.Item.ItemType = ListItemType.EditItem Then

    '        ' Item Types
    '        Dim myTypeDropDown As DropDownList
    '        myTypeDropDown = CType(e.Item.FindControl("seluserid"), DropDownList)

    '        myTypeDropDown.SelectedIndex = myTypeDropDown.Items.IndexOf(myTypeDropDown.Items.FindByText(seluserid))

    '    End If
    'End Sub





End Class
I need to see your aspx code for the grid also.  What, specifically is the error and where in the code is the error occurring?  I don't see a function to get the currently selected item.
Avatar of dash420

ASKER

this my datagrid control, as already told there is no SelectedIndex method here. If i put SelectedIndex in datagrid it is giving error like "unable to declare runtime properties". where to invoke SelectedIndex method, hope you can make out what is my problem.

<asp:DataGrid id="dgBookList" Width="600" Runat="server" AllowCustomPaging="False" AutoGenerateColumns="False" PagerStyle-Visible="true" HeaderStyle-CssClass="GRIDTH" AlternatingItemStyle-BackColor="lightgrey" BackColor="white" CellPadding="2" CellSpacing="2" DataKeyField="book_number" PagerStyle-Position="TopAndBottom" PagerStyle-Mode="NumericPages" PagerStyle-HorizontalAlign="Right" OnPageIndexChanged="DG_paged" OnEditCommand="doItemEdit" OnUpdateCommand="doItemUpdate" OnCancelCommand="doItemCancel" GridLines="None">
                    <Columns>
                         <asp:BoundColumn DataField="book_number" HeaderText="Book No" ReadOnly="True"></asp:BoundColumn>
                         <asp:TemplateColumn HeaderText="Book Title">
                              <ItemTemplate>
                                   <asp:Label Text='<%#Container.DataItem("title_name")%>' Runat="server" ID="Label1">
                                   </asp:Label>
                              </ItemTemplate>
                              <EditItemTemplate>
                                   <asp:TextBox ID ="txtTitle" Text='<%#Container.DataItem("title_name")%>' Runat="server"/>
                              </EditItemTemplate>
                         </asp:TemplateColumn>
                         <asp:TemplateColumn HeaderText="Author Name">
                              <ItemTemplate>
                                   <asp:Label Text='<%#Container.DataItem("author_name")%>' Runat="server" ID="Label2">
                                   </asp:Label>
                              </ItemTemplate>
                              <EditItemTemplate>
                                   <asp:TextBox ID ="txtAuthor" Text='<%#Container.DataItem("author_name")%>' Runat="server"/>
                              </EditItemTemplate>
                         </asp:TemplateColumn>
                         <asp:TemplateColumn HeaderText="Author Name">
                              <ItemTemplate>
                                   <asp:Label Text='<%#Container.DataItem("Publisher")%>' Runat="server" ID="Label3">
                                   </asp:Label>
                              </ItemTemplate>
                              <EditItemTemplate>
                                   <asp:TextBox ID ="txtPublisher" Text='<%#Container.DataItem("Publisher")%>' Runat="server"/>
                              </EditItemTemplate>
                         </asp:TemplateColumn>
                         <asp:BoundColumn DataField="no_of_copies" HeaderText="Copies"></asp:BoundColumn>
                         <asp:TemplateColumn HeaderText="Author Name">
                              <ItemTemplate>
                                   <asp:Label Text='<%#Container.DataItem("user_id")%>' Runat="server" ID="lbluserId">
                                   </asp:Label>
                              </ItemTemplate>
                              <EditItemTemplate>
                                   <asp:DropDownList Runat="server" Id="selUser"
                                DataSource='<%#GetUser()%>'
                                DataValueField="user_id" />
                              </EditItemTemplate>
                         </asp:TemplateColumn>
                         <asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />
                    </Columns>
               </asp:DataGrid>
ASKER CERTIFIED SOLUTION
Avatar of wiseguy_2112
wiseguy_2112

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
Avatar of dash420

ASKER

Hi

="<%# GetSelIndex(Container.DataItem("userid")) %>" is failing if it is null. how to avoid it.
error is like this
Cast from type 'DBNull' to type 'String' is not valid.

as GetSelIndex function signature is like
Function GetSelIndex(ByVal FieldId As String)

 
Avatar of dash420

ASKER

hi gorgot to write this now able to select the value in drop down. only if it null it is giving error.
Avatar of dash420

ASKER

Don't mind, How to validate in the datagrid. like suppose user enter varchar in the integer field.
Avatar of dash420

ASKER

i able to solve null problem. Do u know how to validate data grid while editing. like user enter varchar where fields is number.

Thanks for the help.

regards,
Dash
Sorry Guys ... Just got back to this Forum.

Looks like you guys figred it out. Unfortunately, there is no way to use validation controls when you use in-place editing on a datagrid.

The validation controls seem to be tied to a control on the form. Since techincally not all the datagrid controls are instantiated, the validation controls have problems linking to the correct one.

I assume you could dynamically create the validation controls at run-time. However, I have not been successful at doing that.

Regardless, I code my own validation as part of the update of the datagrid.

Good luck :)