?
Solved

Dropdrown in datagrid

Posted on 2003-02-27
16
Medium Priority
?
353 Views
Last Modified: 2009-12-16
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.

0
Comment
Question by:dash420
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 2
  • +1
16 Comments
 
LVL 6

Expert Comment

by:CarlosMu
ID: 8040951
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
0
 
LVL 2

Expert Comment

by:wiseguy_2112
ID: 8042329
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

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20509280.html

0
 
LVL 2

Expert Comment

by:wiseguy_2112
ID: 8042347
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
0
More Than Just A Video Library

Train for your certification. Learn the latest DevOps tools. Grow your skillset to do better work.

At Linux Academy, we release new training modules every week so you'll always be up to date on the latest tech.

 
LVL 3

Expert Comment

by:Frostbyte_Zero
ID: 8044585
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.
0
 
LVL 6

Author Comment

by:dash420
ID: 8054969
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.  

"


0
 
LVL 6

Author Comment

by:dash420
ID: 8054981
hi  wiseguy_2112

i tried your method it is also fails. givng error something like uanble to declare runtime property
0
 
LVL 2

Expert Comment

by:wiseguy_2112
ID: 8055034
post your code (just the itemtemplate and you code behind) and we'll try to figure out what the problem is.

0
 
LVL 6

Author Comment

by:dash420
ID: 8055058
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
0
 
LVL 2

Expert Comment

by:wiseguy_2112
ID: 8057978
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.
0
 
LVL 6

Author Comment

by:dash420
ID: 8062074
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>
0
 
LVL 2

Accepted Solution

by:
wiseguy_2112 earned 300 total points
ID: 8062242
Where are you trying to put the SelectedIndex?

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

There is a SelectedIndex property, I've used it and the guy who's question I answered earlier used it.  Make sure it's inside the <EditItemTemplate>.

Try it again and if it doesn't work, post your code with it in there.
0
 
LVL 6

Author Comment

by:dash420
ID: 8062463
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)

 
0
 
LVL 6

Author Comment

by:dash420
ID: 8062470
hi gorgot to write this now able to select the value in drop down. only if it null it is giving error.
0
 
LVL 6

Author Comment

by:dash420
ID: 8062487
Don't mind, How to validate in the datagrid. like suppose user enter varchar in the integer field.
0
 
LVL 6

Author Comment

by:dash420
ID: 8064020
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
0
 
LVL 3

Expert Comment

by:Frostbyte_Zero
ID: 8064904
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 :)

0

Featured Post

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question