Locating Textox in Listview that is one of mutiple Textboxes and Records

hsmith825
hsmith825 used Ask the Experts™
on
I am having trouble locating the specific Textbox that is in ListView in a record that is one of many that are readd in.  The key code snipet is attached.  I only ahoq one of the four textboxes since all the texboxes are the same but with different ID.

Using the code attached, I can locate the TextBox if only one record is read.   If I increase it to two or more I do not locate the correct text.  I included a Button in each <ItemTemplate>.  The User selects the desired record by pushing the correct Button.  I had asssumed that this would identify the target record in the .SelectedIndexChanged event.  It doesn't unless their is only one record.

Thanks for any help you can provide.
Hsmith825
<asp:ListView ID="Preference" runat="server" DataSourceID="SqlprefDataSource2" 
        DataKeyNames="Reviewer_UserID">
 
<ItemTemplate>
<asp:TextBox ID="TextShare_Name" CssClass="cnotesl" runat="server" Text='<%# Eval("Share_Name") %>' ReadOnly="True">
                  </asp:TextBox>
<asp:Button ID="ButtonPreferenceedit" Type="Submit" ValidationGroup="Preference" OnClick="Preference_SelectedIndexChanged"  runat="server" Text="Selection" />
</ItemTemplate>
 
<asp:SqlDataSource ID="SqlprefDataSource2" runat="server" OnSelecting="SqlprefDataSource2_Selecting" 
        ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>" 
        SelectCommand="SELECT Reviewer_UserID, UserID, Share_Name, Reviewer_Name, Review_Start_Date, Last_Review_Date, Type_Review, Review_Cancel_Date, Enteredby, Udate, ShareID FROM Share WHERE (Reviewer_UserID = @Reviewer_UserID) ORDER BY Share_Name">
 
Code behind:
 Protected Sub Preference_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Preference.SelectedIndexChanged
Txpreference = DirectCast(Preference.Items.Item(i).FindControl("Type_Review"), TextBox)
saccess = DirectCast(Preference.Items.Item(i).FindControl("HiddenShareID"), TextBox)
TxUserID = DirectCast(Preference.Items.Item(i).FindControl("TextHidden"), TextBox)
TxUserName = DirectCast(Preference.Items.Item(i).FindControl("TextShare_Name"), TextBox)

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
use bindingmanager it is to much easier than going directly to the text box..


 private void Form1_Load(object sender, System.EventArgs e) {
         string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
         string sql = @"select * from employee ";

         SqlConnection conn = new SqlConnection(connString);
         SqlDataAdapter da = new SqlDataAdapter(sql, conn);
         da.Fill(dataSet1, "employee");

         textBox1.DataBindings.Add("text", dataSet1, "employee.firstname");
         textBox2.DataBindings.Add("text", dataSet1, "employee.lastname");
 
         bMgr = this.BindingContext[dataSet1, "employee"];
      }

      private void buttonNext_Click(object sender, System.EventArgs e) {
         bMgr.Position += 1;    
      }

      private void buttonBack_Click(object sender, System.EventArgs e) {
         bMgr.Position -= 1;
      }


source :http://www.java2s.com/Code/CSharp/Database-ADO.net/NavigatethebindeddatausingBindingManagerBase.htm

Author

Commented:
Sorry but if would be very helpful if you could show the solution in Visual Basic.  That is the only language I know.

Thanks!!!

Commented:

example using VB.Net: the main idea is to use the Binding manager to access the DataList Data instead of goint directly to the textboxes...
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim connString As String = "server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"
Dim sql As String = "select * from employee " 
Dim conn As New SqlConnection(connString)
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(dataSet1, "employee")
textBox1.DataBindings.Add("text", dataSet1, "employee.firstname")
textBox2.DataBindings.Add("text", dataSet1, "employee.lastname")
bMgr = Me.BindingContext(dataSet1, "employee")
End Sub
Private Sub buttonNext_Click(ByVal sender As Object, ByVal e As System.EventArgs)
bMgr.Position += 1
End Sub
Private Sub buttonBack_Click(ByVal sender As Object, ByVal e As System.EventArgs)
bMgr.Position -= 1
End Sub
 
 
here is another example from microsoft:

Private Sub GetBindingManagerBase
   ' CustomersToOrders is the RelationName of a DataRelation.
   ' Therefore, the list maintained by the BindingManagerBase is the
   ' list of orders that belong to a specific customer in the
   ' DataTable named Customers, found in DataSet.
   myBindingManagerBase = Me.BindingContext(DataSet1, _
   "Customers.CustomersToOrders")
   ' Adds delegates to the CurrentChanged and PositionChanged events.
   AddHandler myBindingManagerBase.PositionChanged, _
   AddressOf BindingManagerBase_PositionChanged
   AddHandler myBindingManagerBase.CurrentChanged, _
   AddressOf BindingManagerBase_CurrentChanged
End Sub
Private Sub BindingManagerBase_PositionChanged _
(sender As Object, e As EventArgs)
   ' Prints the new Position of the BindingManagerBase.
   Console.Write("Position Changed: ")
   Console.WriteLine(CType(sender, BindingManagerBase).Position)
End Sub
Private Sub BindingManagerBase_CurrentChanged _
(sender As Object, e As EventArgs)
   ' Prints the new value of the current object.
   Console.Write("Current Changed: ")
   Console.WriteLine(CType(sender, BindingManagerBase).Current)
End Sub
Private Sub MoveNext
   ' Increments the Position property value by one.
   myBindingManagerBase.Position += 1
End Sub
Private Sub MovePrevious
   ' Decrements the Position property value by one.
   myBindingManagerBase.Position -= 1
End Sub
Private Sub MoveFirst
   ' Goes to the first row in the list.
   myBindingManagerBase.Position = 0
End Sub
Private Sub MoveLast
   ' Goes to the last row in the list.
   myBindingManagerBase.Position = _
   myBindingManagerBase.Count - 1
End Sub
source :
http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingmanagerbase(VS.71).aspx 
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Author

Commented:
Pepepaco,

I understand your solution.  The problem in this case is I still need to know which record the user has choosen.  The user is choosing one record from many.  I need a way of knowing which record the user has choosen.  I was using the Select button OnClick event to let me know.  I think I will need to identify from the button the record chosen.  This leads me back to locating the textbox unless I misunderstood your solution.

Thanks!!!

Author

Commented:
I sent my last comment before I had a chance to look at what you just sent.  Let me take a look and see if this helps.

Thanks!!!

Author

Commented:
I undeerstand the bondingmanager solution.  But it will not work here.  My situation is as follows:
Record 1:  
Submit Button
Record 2
Submit Button
............

Record n
Submit button

The user reeads in a number of records that are displayed in Listview.  The user may abitrarily click a button.  I have know idea what the increment/decrement is.  

Th solution you have assume  the User clicks the button to identify each record and in the order that they appear.  That is not the case here.  The customer may advance 8 records witout clicking a button which will make it difficult to synchromize this way.

If I understand your solution, I think it is not an alternative to m my locating the textbox.  Any other ideas is appreciated.

Thanks!!!

Commented:

I could think a solution that might not be very easy or elegant, but im sure it works. since every button has one ID, then you must add a JavaScript that pass the ID to a function, this function should pass the Id to a hidden text box, the do postback , on the server side you catch that ID and this way you know the row number user clicked, check the binding manager to get the values by rowid, and thats it. you get your data...let me work on an example of this..
Regards.
 
 

Author

Commented:
Thanks!!!

Commented:

hoo well i found better solution...

extracted from http://msdn.microsoft.com/en-us/library/y200hyx2(VS.71).aspx

The following example shows how you can respond to a button click in a DataList control. In the example, the ItemTemplate contains an ImageButton control that displays a shopping cart. The button sends the command AddToCart. The ItemCommand event handler determines which button was clicked, and  if it was the shopping cart button  performs the appropriate logic.


' Visual Basic
Private Sub DataList1_ItemCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
   If (e.CommandName = "AddToCart") Then
      ' Add code here to add the item to the shopping cart.
      ' Use the value of e.Item.ItemIndex to find the data row
      ' in the data source.
    End If
End Sub

let me know if it works for you.. or I can modify it to my first approach
Commented:

sorry the example is on DataList not Listview and unfortunately i dont have framework 3.5 installed however here is a good example from microsoft:
http://msdn.microsoft.com/en-us/library/bb515103.aspx
 hope this helps.
 

Author

Commented:
Great!!!

This looks outstanding.  As you suggested, can you modify the solution to use your first approach?  That will help ensure I get it correct.

Thanks!!!

Commented:
here is the example:

you can move the section <script runat="server"> to the code behind if you want.
as you can see this example is more easy and elegant approach since we dont have to hack using javascript anymore, using adding a command text and catching it at OnItemCommand you can access the row data.
let me know if this works for you.

source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemcommand.aspx

Another good example is here: http://www.codeproject.com/KB/webforms/CompleteListView.aspx


<%@ Page language="VB" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
  Protected Sub EmployeesListView_OnItemCommand(ByVal sender As Object, _
  ByVal e As ListViewCommandEventArgs)
 
    If String.Equals(e.CommandName, "AddToList") Then
 
      ' Verify that the employee ID is not already in the list. If not, add the
      ' employee to the list.
      Dim dataItem As ListViewDataItem = CType(e.Item, ListViewDataItem)
      Dim employeeID As String = _
        EmployeesListView.DataKeys(dataItem.DisplayIndex).Value.ToString()
 
      If SelectedEmployeesListBox.Items.FindByValue(employeeID) Is Nothing Then
        Dim item As ListItem = _
          New ListItem(e.CommandArgument.ToString(), employeeID)
        SelectedEmployeesListBox.Items.Add(item)
      End If
 
    End If
 
  End Sub
</script>
 
<html  >
<head id="Head2" runat="server">
    <title>Employee List</title>
  </head>
  <body>
    <form id="form1" runat="server">
      <asp:ListView runat="server" 
        ID="EmployeesListView"
        OnItemCommand="EmployeesListView_OnItemCommand"
        DataSourceID="EmployeesDataSource" 
        DataKeyNames="EmployeeID">
        <LayoutTemplate>
          <table runat="server" id="tblEmployees" 
                 cellspacing="0" cellpadding="1" width="440px" border="1">
            <tr id="itemPlaceholder" runat="server"></tr>
          </table>
          <asp:DataPager ID="EmployeesDataPager" runat="server" PageSize="10">
            <Fields>
              <asp:NumericPagerField />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td>
              <asp:Label runat="server" ID="NameLabel" 
                Text='<%#Eval("LastName") & ", " & Eval("FirstName") %>' />
            </td>
            <td style="width:80px">
              <asp:LinkButton runat="server" 
                ID="SelectEmployeeButton" 
                Text="Add To List" 
                CommandName="AddToList" 
                CommandArgument='<%#Eval("LastName") & ", " & Eval("FirstName") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
 
      <br /><br />
      <b>Selected Employees:</b><br />
      <asp:ListBox runat="server" ID="SelectedEmployeesListBox" Rows="10" Width="300px" />
 
      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->       
      <asp:SqlDataSource ID="EmployeesDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [EmployeeID], [FirstName], [LastName]
                       FROM HumanResources.vEmployee
                       ORDER BY [LastName], [FirstName], [EmployeeID]">
      </asp:SqlDataSource>
    </form>
  </body>
</html>

Open in new window

Author

Commented:
I have spend a couple of days trying to get this solution to work but I am still having problems.  I have tried a number of variations.  attached is the latest code snipett.  I am getting compiler errors with the suggested solution with all variations I have tried.
To restate the problem: I am trying to locate specific Textboxes that are in a listview control.  I have read in a number of records.  I have a solution that works if I have only read one record.  This solution is listed first.
The second snippet is my attempt to apply the last suggested solution.
Thanks for helping.

This smipped of code behind works if I have only read one record but does not work with two or more records.
 Protected Sub Preference_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Preference.SelectedIndexChanged
        Dim saccess As TextBox
        Dim Txpreference As TextBox
        Dim TxUserID As TextBox
        Dim TxUserName As TextBox
        For i = 0 To Preference.Items.Count - 1
 
            Txpreference = DirectCast(Preference.Items.Item(i).FindControl("Type_Review"), TextBox)
            saccess = DirectCast(Preference.Items.Item(i).FindControl("HiddenShareID"), TextBox)
            TxUserID = DirectCast(Preference.Items.Item(i).FindControl("TextHidden"), TextBox)
            TxUserName = DirectCast(Preference.Items.Item(i).FindControl("TextShare_Name"), TextBox)
 
        Next
        Session("S_Perference") = Txpreference.Text
        Session("S_Active_UserID") = TxUserID.Text
        Session("S_UserName") = TxUserName.Text
        Label3.Text = TxUserName.Text
End Sub
 
The code behind built on the suggested solution id below.  I am having compiler areas since the solution requires me to use the nameof the Textboxes which must be declared.
 
Protected Sub Preference_OnItemCommand(ByVal sender As Object, _ByVal e As ListViewCommandEventArgs)
        If Not String.Equals(e.CommandName, "Select") Then Exit Sub
        Dim saccess As String
        Dim Txpreference As String
        Dim TxUserID As String
        Dim TxUserName As String
 
        Dim DataItem As ListViewDataItem = CType(e.item, ListViewDataItem)
        Dim ShareID As String = Preference.DataKeys(DataItem.DisplayIndex).Value.ToString()
        Dim Type_Review As String = Preference.DataKeys(DataItem.DisplayIndex).Value.ToString()
        Dim UserID As String = Preference.DataKeys(DataItem.DisplayIndex).Value.ToString()
        Dim Share_name As String = Preference.DataKeys(DataItem.DisplayIndex).Value.ToString()
 
        saccess = HiddenShareID.Items.Item(i)FindByValue(ShareID)
        Txpreference = Type_Review.Items.Findvalue(Type_Review)
        TxUserID = TextHidden.Items.Findvalue(UserID)
        TxUserName = TextShare_Name.Items.Findvalue(Share_Name)
        'Label3.Text = TxUserName.Text
End Sub
 
The html is the same for both an a snippet is shown below.  I show one of the four text boxes that I am trying to locate.  The boxes appear in each record with other information.
 
<asp:ListView ID="Preference" runat="server" DataSourceID="SqlprefDataSource2" 
        DataKeyNames="Reviewer_UserID">
 <ItemTemplate>
<asp:TextBox ID="TextShare_Name" ValidationGroup="Preference" CssClass="cnotesl" runat="server" Text='<%# Eval("Share_Name") %>' ReadOnly="True"></asp:TextBox>
(Four text boxes of interest appear in this section.)
<asp:Button ID="ButtonPreferenceedit" Type="Submit" ValidationGroup="Shareupdate" OnClick="Preference_SelectedIndexChanged"  runat="server" Text="Select" />
</ItemTemplate>
</asp:ListView>
      <asp:SqlDataSource ID="SqlprefDataSource2" runat="server" OnSelecting="SqlprefDataSource2_Selecting" 
        ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>" 
                SelectCommand="SELECT Reviewer_UserID, UserID, Share_Name, Reviewer_Name, Review_Start_Date, Last_Review_Date, Type_Review, Review_Cancel_Date, Enteredby, Udate, ShareID FROM Share WHERE (Reviewer_UserID = @Reviewer_UserID) ORDER BY Share_Name">
       <SelectParameters>
           <asp:Parameter Name="Reviewer_UserID" />
       </SelectParameters>
    </asp:SqlDataSource>

Open in new window

I did not receive a solution that worked.

I changed the application so that pm clicking the taargeted textbox was moved to the EditItemTemplate.  Then I used the solution I have that works if only one record is in the space.  This workaround solved my problem.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial