ListView 'SelectedIndexChanged' situation

I've got a ListView on my Windows Form that displays information from an Access database. I am trying to show the data in textboxes when a row in the listview is clicked. The code I've typed so far works, to an extent . . .

When I click on a row, the lase record in the database is displayed in the textboxes. I know that I need to use the ListView_SelectedIndexChanged event, but where I'm getting confused is how to select the correct item index  I've tried several properties/events/ to get this to work and I'm about to go bald trying to figure this out, can someone point out to me just what I'm doing or not doing

   private void listViewMemberList_SelectedIndexChanged(object sender, System.EventArgs e)
   {
     string status = "";
     string indx = this.listViewMemberList.SelectedItems.ToString();
     string select = strSelectAll +
             ( "WHERE SAMS_ID = " + indx );
     try
     {
      strConnect = new OleDbConnection( strDbConnect );
      ds1889 = new DataSet();
      da1889 = new OleDbDataAdapter( strSelectAll, strConnect );
      da1889.Fill( ds1889, TableName );
      labelCurrentStatus.Font = new Font( labelCurrentStatus.Font, FontStyle.Bold );
      labelCurrentStatus.Text = "Current Status: Locate . . . ";
      
      foreach ( DataRow dr in ds1889.Tables[0].Rows )
      {
        label1889Id.Text = dr["SAMS_ID"].ToString();
        switch ( dr["MembershipStatus"].ToString() )
        {
         case "A":
           status = "Active";
           break;
         case "I":
           status = "InActive";
           break;
         case "L":
           status = "Life";
           break;
         case "P":
           status = "Provisional";
           break;
        }
        textboxSamsId.Text = dr["SAMS_ID"].ToString();
        textBoxMemberName.Text = dr["LastName"] + ", " + dr["FirstName"].ToString();
        textBoxMemberAddress.Text = dr["Address"].ToString();
        textBoxAddressCity.Text = dr["City"].ToString();
        textBoxAddressState.Text = dr["State"].ToString();
        textBoxAddressZipCode.Text = dr["ZipCode"].ToString();
        textBoxPhoneNumber.Text = dr["HomePhone"].ToString();
        textBoxEmailAddress.Text = dr["EmailAddress"].ToString();
        textBoxMembershipStatus.Text = status;
        textBoxDateJoined.Text = dr["DateJoined"].ToString();
        textBoxNatlDuesPaidDate.Text = dr["NationalDuesPaidDate"].ToString();
        textBoxNatlCheckNumber.Text = dr["NationalDuesChekNum"].ToString();
        textBoxPostDuesPaidDate.Text = dr["PostDuesPaidDate"].ToString();
        textBoxPostCheckNumber.Text = dr["PostDuesChekNum"].ToString();
      }
      labelCurrentStatus.Text = "Current Status: Ready . . . ";
     }
    
     catch ( OleDbException oex )
     {
      Mess


Answer this question

ListView 'SelectedIndexChanged' situation

  • JohnMathewmathan

    That should work - I've done this many time before with ListViews.

    Just remember that you need to store for each ListViewItem the primary key (unique identifier) for a matching record in your database. I use the Tag property of the ListViewItem to store this information. I can then retrieve it later when an individual ListViewItem is selected from the ListView.

    By the way, I modified the preceding code to use a String primary key instead of an integer.



  • vbtricks

    Thank you DotNet, I appreciate your help.

     

    Rhubarb



  • Kristijan_M

    I get an error that I still don't understand fully. 

    "NullReference Exception"
    "Object reference not set to an instance of an object."

    What does this mean   The line "string strPrimaryKey . . ." is highlighted.

     

    if ( this.listViewMemberList.SelectedIndices.Count > 0 )
    {
          string strPrimaryKey = this.listViewMemberList.SelectedItems[0].Tag.ToString();
          StringBuilder sbSQL = new StringBuilder( "SELECT * FROM Post1889 WHERE SAMS_ID = ");
          sbSQL.Append( strPrimaryKey);
    }

     

     



  • Frank Hodgkinson

    I'm sorry, I should have said this at the start.  Right now I'm so frustrated! 

    The key to the database is the four character field (SAMS_ID), in column one of the ListView.  I thought it would be a 'piece of cake' to implement, but I've stumbled along the way.

    I'm gonna try out your suggestion though, at this point, I'll try anything.



  • santosh kumar gupta

    That means you didn't set the Tag of each ListViewItem to the primary key.

    In other words, this.listViewMemberList.SelectedItems[0].Tag = null



  • Chao Gao

    I believe the problem is that you need to store a primary key for each database record in the ListView. This primary key can then be used to find a matching record in the database like this:

    private void SomeMethod()
    {
        // Get some sample data to populate list view with here...
        DataSet ds = new DataSet();
        DataTable tbl = new DataTable("tblTest");
        tbl.Columns.Add("ID").Unique = true; // the Primary Key of the record
        tbl.Columns.Add("Col1");
        for (int i = 1; i <= 20; i++)
        {
            DataRow rowNew = tbl.NewRow();

            rowNew["ID"] = "ID" + i.ToString();
            rowNew["Col1"] = "Number #" + i.ToString();
            tbl.Rows.Add(rowNew);
        }
        ds.Tables.Add(tbl);

        // Populate ListView
        foreach (DataRow row in tbl.Rows)
        {
            ListViewItem lvi = new ListViewItem();
            // ********* Store primary key ID of database record in the Tag of the ListViewItem *********:
            lvi.Tag = row["ID"];
            // Store display data here:
            lvi.Text = row["Col1"].ToString();
            this.listView1.Items.Add(lvi);
        }

        // Setup ListView properties:
        this.listView1.MultiSelect = false;

        // Setup ListView SelectedIndexChanged Event Handler:
        this.listView1.SelectedIndexChanged += new EventHandler(this.listView1_SelectedIndexChanged);
    }

    private void listView1_SelectedIndexChanged(Object Sender, EventArgs e)
    {
        if (this.listView1.SelectedIndices.Count > 0)
        {
            // Get primary key ID here:
            String strPrimaryKey = this.listView1.SelectedItems[0].Tag.ToString();
            // Setup SQL query string here:
            StringBuilder sbSQL = new StringBuilder("SELECT * FROM MyTable WHERE ID = ");
            sbSQL.Append(strPrimaryKey);
            // Do the rest...

        }
    }



  • ListView 'SelectedIndexChanged' situation