• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 471
  • Last Modified:

Passing Values from Dropdownlist in Datagrid

I have a 2 dropdownlists in a datagrid which can have 1..N number of rows in it.  The user can change the value in of any of the dropdownlists then press save or cancel.  Upon saving the selections I need to update database records based on the dropdownlists.  What I don't want to do is postback to the server after a dropdownlist is altered thats why I am using a button to handle this event (saving).  I have the following questions:

1. Is there a way I can update only the records that have a changed value in the dropdownlist (ie value not equal to the index 0, in this case value = "")?
2. How can I get the value of the bound column for a given row in the datagrid once the user presses save?
3. Since there are multiple dropdownlists is there a way to get the value of each for a particular row if the id's of the dropdownlist are the same?  Or would it be cleaner to give them different ID's? (ie dateDropList, dateDropList1)
4. The bound column consists of 2 fields concatenated, is there a way to parse the data in the first column?  For instance I want to get the string up to the ',' and the string after and assign them to 2 different variables.

Below is the datagrid code & submit button where I think I need the help..

<ASP:DataGrid id="MyDataGrid" runat="server"
    Width="855"
    BackColor="#cccccc"
    BorderColor="#FFFFFF"
    ShowFooter="false"
    CellPadding=3
    CellSpacing="0"
    Font-Name="Verdana" Height="16px" BorderWidth="2"
    Font-Size="11px"
    HeaderStyle-BackColor="#999999" HeaderStyle-Height="16px" HeaderStyle-Font-Size="11px"
    EnableViewState="false"
    HorizontalAlign="Center"
    AutoGenerateColumns="false"
>

<columns>

<asp:TemplateColumn>
      <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
      <headertemplate>
            <table>
            <td><b>User</b></td>
            </table>
      </headertemplate>
      <itemtemplate>
            <table>
            <td><%# Container.DataItem( "LastName" )%>,</td><td><%# Container.DataItem( "FirstName" )%></td>
            </table>
      </itemtemplate>
</asp:TemplateColumn>

<asp:BoundColumn
      HeaderText="User ID"
      DataField="UserID"  
      HeaderStyle-Font-Bold="true"
      HeaderStyle-HorizontalAlign="Center" />

<asp:TemplateColumn>
      <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
      <headertemplate>
            <table>
            <td><b><%# curDate.ToString( "d" ) %></b></td>
            </table>
      </headertemplate>
      
      <itemstyle HorizontalAlign="Center"></itemstyle>
      <itemtemplate>
            <asp:DropDownList ID="dateDropList" runat="server">
                  <asp:ListItem Selected="true" Text=""></asp:ListItem>
                  <asp:ListItem Text="1"></asp:ListItem>
                  <asp:ListItem Text="2"></asp:ListItem>
                  <asp:ListItem Text="3"></asp:ListItem>
            </asp:DropDownList>
      </itemtemplate>
</asp:TemplateColumn>

<asp:TemplateColumn>
      <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
      <headertemplate>
            <table>
            <td><b><%# incDate1.ToString( "d" ) %></b></td>
            </table>
      </headertemplate>
      
      <itemstyle HorizontalAlign="Center"></itemstyle>
      <itemtemplate>
            <asp:DropDownList ID="dateDropList" runat="server">
                  <asp:ListItem Selected="true" Text=""></asp:ListItem>
                  <asp:ListItem Text="1"></asp:ListItem>
                  <asp:ListItem Text="2"></asp:ListItem>
                  <asp:ListItem Text="3"></asp:ListItem>
            </asp:DropDownList>
      </itemtemplate>
</asp:TemplateColumn>

Sub SubmitBtn_Click(Sender As Object, E As EventArgs)                        
            'logic to get the bound column values & parse as well as getting the dropdownlist value(s)
End Sub
0
egdigital
Asked:
egdigital
  • 6
  • 6
2 Solutions
 
allanau20Commented:
Here's a really good link for your solution:

http://www.c-sharpcorner.com/Code/2003/Jan/AccessDataGridVal.asp

1. Yes
2. Refer to link
3. Should have different IDs
4. Here's how you parse a string:

    Dim str as string = "one;two;three"
    Dim MixedStr  as String()
    Dim item as String

    MixedStr = str.Split(";")

    For Each item in MixedStr
        Response.Write("<li>" + item)
        'or do something with the item
    Next

Then your output looks like this:
      one
      two
      three

HtH

0
 
egdigitalAuthor Commented:
thanks for the infor allanau20, would you happen to know have a link which outlines this in vb instead of c# & according to this link the way to check if the user has selected a particular value for the dropdown would be to check the value for each of the dropdowns so in this case value not = to ""?
0
 
allanau20Commented:
Here's a 'translator' from C# to VB.Net:

http://authors.aspalliance.com/aldotnet/examples/translate.aspx

Just paste the C# code in the textarea and hit on the 'translate' and it will give u the vb.net. However, there's some small flaw in it but you'll figure it out.

HtH.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
allanau20Commented:
I would use dateDropList.SelectedIndex() <> 0

It would tell me it has changed.
0
 
egdigitalAuthor Commented:
one last question on this.. would i access the templatecolumn in the same fashion as I would access a bound column ie dataGridItem.Cells(0).Text?
0
 
egdigitalAuthor Commented:
When I try to get value of the first column using Dim stuName As [String] = dataGridItem.Cells(0).Text, no value is returned.  I able to get the values of the dropdownlists just fine, it is the TemplateColumn where I am having a problem.  
0
 
allanau20Commented:
Sorry egdigital, I haven't accessed the TemplateColumn. If I find anything, I'll let u know. I hope other experts can help u from here.
0
 
sachiekCommented:
A simple example which is found in asp.net site itself. check this. They had used dropdownlist and that can be grabbed without been posted back.

Hope it helps. But you still need to have unique ID for each dropdownlist.
I had commented out few lines inorder to just work when you paste this code to any virtual directory in your PC.
Modify the connectionstring accordingly.

_____________________datagrid8.aspx------------------------------------------------------------------
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>

<script language="VB" runat="server">

    Dim MyConnection As SqlConnection
    Public StateIndex As Hashtable

    Sub Page_Load(Src As Object, E As EventArgs)

        myConnection = new SqlConnection("Server=yourserver;Database=pubs;User ID=sa;Password=;Trusted_Connection=False")

        If Not (IsPostBack)
            BindGrid()
        End If

        StateIndex = New Hashtable()
        StateIndex("CA") = 0
        StateIndex("IN") = 1
        StateIndex("KS") = 2
        StateIndex("MD") = 3
        StateIndex("MI") = 4
        StateIndex("OR") = 5
        StateIndex("TN") = 6
        StateIndex("UT") = 7
    End Sub

    Public Function GetStateIndex(StateName As String) As Integer

        If StateIndex(stateName) <> Nothing
            Return CInt(StateIndex(stateName))
        Else
            Return 0
        End If
    End Function

    Sub MyDataGrid_Edit(Sender As Object, E As DataGridCommandEventArgs)

        MyDataGrid.EditItemIndex = CInt(E.Item.ItemIndex)
        BindGrid()
    End Sub

    Sub MyDataGrid_Cancel(Sender As Object, E As DataGridCommandEventArgs)

        MyDataGrid.EditItemIndex = -1
        BindGrid()
    End Sub

    Sub MyDataGrid_Update(Sender As Object, E As DataGridCommandEventArgs)

        Dim DS As DataSet
        Dim MyCommand As SqlCommand

        Dim UpdateCmd As String = "UPDATE Authors SET au_id = @Id, au_lname = @LName, " & _
             "au_fname = @FName, phone = @Phone, address = @Address, city = @City, " & _
             "state = @State, zip = @Zip, contract = @Contract where au_id = @Id"

        MyCommand = New SqlCommand(UpdateCmd, MyConnection)

        MyCommand.Parameters.Add(New SqlParameter("@Id", SqlDbType.NVarChar, 11))
        MyCommand.Parameters.Add(New SqlParameter("@LName", SqlDbType.NVarChar, 40))
        MyCommand.Parameters.Add(New SqlParameter("@FName", SqlDbType.NVarChar, 20))
        MyCommand.Parameters.Add(New SqlParameter("@Phone", SqlDbType.NChar, 12))
        MyCommand.Parameters.Add(New SqlParameter("@Address", SqlDbType.NVarChar, 40))
        MyCommand.Parameters.Add(New SqlParameter("@City", SqlDbType.NVarChar, 20))
        MyCommand.Parameters.Add(New SqlParameter("@State", SqlDbType.NChar, 2))
        MyCommand.Parameters.Add(New SqlParameter("@Zip", SqlDbType.NChar, 5))
        MyCommand.Parameters.Add(New SqlParameter("@Contract", SqlDbType.NVarChar,1))

        MyCommand.Parameters("@Id").Value = MyDataGrid.DataKeys(CInt(E.Item.ItemIndex))

        Dim Cols As String() = {"LName","FName","Phone","Address","City","Zip"}
        Message.InnerHtml = ""

        Dim I As Integer
        For I = 0 To 5

            Dim CurrentTextBox As System.Web.UI.WebControls.TextBox
            CurrentTextBox = E.Item.FindControl("edit_" & Cols(I))
            Dim ColValue As String = CurrentTextBox.Text

            ' check for invalid values
         /*   Select Case Cols(i)
                Case "LName"
                    If Not InputValidator.IsValidAnsiName(colvalue)
                        Message.InnerHtml &= "ERROR: Last Name - " & InputValidator.AnsiNameErrorString & "<br>"
                    End If
                Case "FName"
                    If Not InputValidator.IsValidAnsiName(colvalue)
                        Message.InnerHtml &= "ERROR: First Name - " & InputValidator.AnsiNameErrorString & "<br>"
                    End If
                Case "Phone"
                    If Not InputValidator.IsValidAnsiPhoneNumber(colvalue)
                        Message.InnerHtml &= "ERROR: Phone - " & InputValidator.AnsiPhoneErrorString & "<br>"
                    End If
                Case "Address"
                    If Not InputValidator.IsValidAnsiAddress(colvalue)
                        Message.InnerHtml &= "ERROR: Address - " & InputValidator.AnsiAddressErrorString & "<br>"
                    End If
                Case "City"
                    If Not InputValidator.IsValidAnsiCityOrState(colvalue)
                        Message.InnerHtml &= "ERROR: City - " & InputValidator.AnsiCityStateErrorString & "<br>"
                    End If
                Case "Zip"
                    If Not InputValidator.IsValidFiveDigitZipCode(colvalue)
                        Message.InnerHtml &= "ERROR: Zip Code - " & InputValidator.AnsiBasicZipCodeErrorString & "<br>"
                    End If
            End Select*/

            ' Check for null values in required fields
            If ColValue = ""
                Message.InnerHtml &= "ERROR: Null values not allowed for " & Cols(i-1) & "<br>"
            End If

            MyCommand.Parameters("@" & Cols(I)).Value = ColValue
        Next

        If Message.InnerHtml <> ""
            Message.Style("color") = "red"
            Return
        End If

        Dim StateDropDownList As DropDownList
        StateDropDownList = E.Item.FindControl("edit_State")
        MyCommand.Parameters("@State").Value = StateDropDownList.SelectedItem.ToString()

        Dim ContractCheckBox As CheckBox
        ContractCheckBox = E.Item.FindControl("edit_Contract")

        If ContractCheckBox.Checked = true
            MyCommand.Parameters("@Contract").Value = "1"
        Else
            MyCommand.Parameters("@Contract").Value = "0"
        End If

        MyCommand.Connection.Open()

        Try
            MyCommand.ExecuteNonQuery()
            Message.InnerHtml = "<b>Record Updated</b><br>" & UpdateCmd
            MyDataGrid.EditItemIndex = -1
        Catch Exp As SqlException
            If Exp.Number = 2627
                Message.InnerHtml = "ERROR: A record already exists with " & _
                    "the same primary key"
            Else
                Message.InnerHtml = "ERROR: Could not update record, " & _
                    "please ensure the fields are correctly filled out"
            End If
            Message.Style("color") = "red"
        End Try

        MyCommand.Connection.Close()

        BindGrid()
    End Sub

    Sub BindGrid()

        Dim DS As DataSet
        Dim MyCommand As SqlDataAdapter
        MyCommand = new SqlDataAdapter("select * from Authors", MyConnection)

        DS = new DataSet()
        MyCommand.Fill(DS, "Authors")

        MyDataGrid.DataSource=DS.Tables("Authors").DefaultView
        MyDataGrid.DataBind()
    End Sub

</script>

<body style="font: 10pt verdana">

  <form runat="server">

    <h3><font face="Verdana">Updating a Row of Data w/ Templated Column</font></h3>

    <span id="Message" EnableViewState="false" style="font: arial 11pt;" runat="server"/><p>

    <ASP:DataGrid id="MyDataGrid" runat="server"
      Width="800"
      BackColor="#ccccff"
      BorderColor="black"
      ShowFooter="false"
      CellPadding=3
      CellSpacing="0"
      Font-Name="Verdana"
      Font-Size="8pt"
      HeaderStyle-BackColor="#aaaadd"
      OnEditCommand="MyDataGrid_Edit"
      OnCancelCommand="MyDataGrid_Cancel"
      OnUpdateCommand="MyDataGrid_Update"
      DataKeyField="au_id"
      AutoGenerateColumns="false"
    >

      <Columns>
        <asp:EditCommandColumn EditText="Edit" CancelText="Cancel"
            UpdateText="Update"  ItemStyle-Wrap="false"/>
        <asp:BoundColumn HeaderText="au_id" SortExpression="au_id"
            ReadOnly="True" DataField="au_id" ItemStyle-Wrap="false"/>
        <asp:TemplateColumn HeaderText="au_lname" SortExpression="au_lname">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "au_lname") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_LName"
                Text='<%# DataBinder.Eval(Container.DataItem, "au_lname") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="au_fname" SortExpression="au_fname">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "au_fname") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_FName"
                Text='<%# DataBinder.Eval(Container.DataItem, "au_fname") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="phone" SortExpression="phone">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "phone") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_Phone"
                Text='<%# DataBinder.Eval(Container.DataItem, "phone") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="address" SortExpression="address">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "address") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_Address"
                Text='<%# DataBinder.Eval(Container.DataItem, "address") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="city" SortExpression="city">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "city") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_City"
                Text='<%# DataBinder.Eval(Container.DataItem, "city") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="state" SortExpression="state">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "state") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:DropDownList runat="server"
                SelectedIndex='<%# GetStateIndex(Container.DataItem("state")) %>'
                id="edit_State">
                  <asp:ListItem>CA</asp:ListItem>
                  <asp:ListItem>IN</asp:ListItem>
                  <asp:ListItem>KS</asp:ListItem>
                  <asp:ListItem>MD</asp:ListItem>
                  <asp:ListItem>MI</asp:ListItem>
                  <asp:ListItem>OR</asp:ListItem>
                  <asp:ListItem>TN</asp:ListItem>
                  <asp:ListItem>UT</asp:ListItem>
            </asp:DropDownList>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="zip" SortExpression="zip">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "zip") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_Zip"
                Text='<%# DataBinder.Eval(Container.DataItem, "zip") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="contract" SortExpression="contract">
          <ItemTemplate>
            <asp:Label runat="server"
                Text='<%# DataBinder.Eval(Container.DataItem, "contract", "{0}") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:CheckBox runat="server" id="edit_Contract"
                Checked='<%# DataBinder.Eval(Container.DataItem, "contract") %>'/>
          </EditItemTemplate>
        </asp:TemplateColumn>
      </Columns>

    </ASP:DataGrid>

  </form>

</body>
</html>
0
 
egdigitalAuthor Commented:
sachiek, do you know how to pull the values from the following TemplateColumn?

<asp:TemplateColumn>
     <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
     <headertemplate>
          <table>
          <td><b>User</b></td>
          </table>
     </headertemplate>
     <itemtemplate>
          <table>
          <td><%# Container.DataItem( "LastName" )%>,</td><td><%# Container.DataItem( "FirstName" )%></td>
          </table>
     </itemtemplate>
</asp:TemplateColumn>

If I use Dim Name As [String] = dataGridItem.Cells(0).Text it returns nothing.
0
 
allanau20Commented:
egdigital, let's try this. Try putting ><%# Container.DataItem( "LastName" )%> and ><%# Container.DataItem( "FirstName" )%> into labels. Then try to access it like this:

Dim lbltest As label
lbltest = CType(e.Item.FindControl("lblName"), label)

To grab what's in the label use lbltest.text

I don't know if this will work, but can you try?

0
 
egdigitalAuthor Commented:
I gave it a shot, converted into a label and attempted to access via: Dim Name As [String] = CType(dataGridItem.FindControl("lblName"), label).Text  which also returns a blank value
0
 
allanau20Commented:
Sorry I can't help u any further.
0
 
egdigitalAuthor Commented:
Thanks for the help allanau20, I just used hidden bound columns instead of attempting to access the templateColumn & that worked.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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