Tuesday, December 10, 2019

Listview


        

private void lvStudents_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
                getRecord(lvStudents.SelectedItems[0].Text);
        }





       


private void getRecord(string studentID)

        {
            if (!ConnectedToDB())
                return;
            string strSQL = "SELECT * FROM tblStudents WHERE Stud_ID = ?";
            OleDbCommand cmdStudents = new OleDbCommand(strSQL, Conn);
            cmdStudents.Parameters.AddWithValue("Stud_ID", studentID);
            OleDbDataReader rdrStudents = cmdStudents.ExecuteReader();

            rdrStudents.Read();
            strID = studentID;
            txtName.Text = rdrStudents["Stud_Name"].ToString();
            txtAddress.Text = rdrStudents["Stud_Address"].ToString();
            txtAge.Text = rdrStudents["Stud_Age"].ToString();
            //assign the stud_course as the selectedValue for the course combobox
            //it will then be reflected in the combobox's text
            cboCourses.SelectedValue = rdrStudents["Stud_Course"].ToString();
            cmdStudents.Dispose();
            Conn.Close();
        }

Listview


Procedure:
1. Draw a ListView in the form and name it lvStudents.
2. Copy the code below the image.


Code:

        private void Form1_Load(object sender, EventArgs e)
        {
            //initialize list view
            lvStudents.GridLines = true;
            lvStudents.View = View.Details;
            lvStudents.FullRowSelect = true;
            lvStudents.Columns.Add("id").Width = 0;
            lvStudents.Columns.Add("StudName").Width = 200;
            fillListView();
            FillCoursesCombo();
        }

        private void fillListView()
        {
            if (!ConnectedToDB())
                return;
            //get all records 
            string strSQL = "SELECT Stud_ID, Stud_Name FROM tblStudents ORDER BY Stud_Name";
            OleDbCommand cmdStudents = new OleDbCommand(strSQL, Conn);
            OleDbDataReader rdrStudents = cmdStudents.ExecuteReader();

            //clear the listview
            lvStudents.Items.Clear();
            //check if it returns any record
            if (rdrStudents.HasRows)
            {
                //iterate thru all records and add each to the listview
                while (rdrStudents.Read())
                {
                    ListViewItem myRow = new ListViewItem(rdrStudents["Stud_ID"].ToString());
                    myRow.SubItems.Add(rdrStudents["Stud_Name"].ToString());

                    lvStudents.Items.Add(myRow);
                }
            }
            //cleanup the mess!
            cmdStudents.Dispose();
            rdrStudents.Close();
            Conn.Close();                    
        }

No comments:

Post a Comment