Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Dropdrown in datagrid

Posted on 2003-02-27
16
Medium Priority
?
354 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
  • 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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…
Suggested Courses

571 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