How to populate datagrid and controls together

DPlug 41 Reputation points
2020-12-16T22:17:53.393+00:00

I am having troubles populating my datagrid along with the controls in my wpf page, when the the page loads, and also how can I navigate from record to record when I click the next and previous buttons, I want the highlighter to move to another record on the datagrid and the controls to change values correspondingly to the datagrid highlighter. I am reading data from SQL server database
This is my code below.The datagrid name is DGAll. Somebody help me evaluate the code below.

        private void StudentRegistrationForm_Loaded(object sender, RoutedEventArgs e)
        {
            StudentConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolDB"].ConnectionString);
            StudentCmd = new SqlCommand();
            StudentCmd.Connection = StudentConn;
            StudentCmd.CommandType = CommandType.StoredProcedure;
            StudentCmd.CommandText = "spStudent_GetAll";
            try
            {
                // Database connection, commands and reader to read and display data from database
                StudentConn.Open();
                studentReader = StudentCmd.ExecuteReader();
                DGAll.ItemsSource = studentReader;

                // Open connection and read data from database
                if (studentReader.Read())
                {

                            TxtbID.Text = studentReader["Id"].ToString();
                            TxtLastName.Text = (string)studentReader["LastName"];
                            TxtFirstName.Text = (string)studentReader["FirstName"];
                            TxtEmail.Text = (string)studentReader["Email"];
                            CboGender.Text = (string)studentReader["Gender"];
                            DtpDateOfBirth.SelectedDate = (DateTime)studentReader["DateofBirth"];
                            DtpDateRegistered.SelectedDate = (DateTime)studentReader["DateRegistered"];
                            TxtPhone.Text = (string)studentReader["MobileNumber"];
                            TxtComment.Text = (string)studentReader["Notes"];
                            CboReligion.Text = (string)studentReader["Religion"];

                            // Extract byte array from database and change it to image
                            imgprofilePicture.Source = GetBitmapImageFromBytes((byte[])studentReader["Image"]);

                            CboSpecialAttention.Text = (string)studentReader["SpecialAttention"];
                            //TxtGuardianID.DataContext = (int)studentReader["GuardianID"];


                }
            }

            catch (Exception ex)
                {
                        // If error occurs
                if (ex is SqlException || ex is SystemException || ex is NullReferenceException || ex is InvalidOperationException)
                    {
                    MessageBox.Show(ex.Message, "Error Establishing Connection to Student Data Service", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            finally
            {
                //Close all database objects
                studentReader.Close();
                StudentCmd.Dispose();
                StudentConn.Close();
                StudentConn.Dispose();
            }
            // Set the app state to view mode
            SetState("View");
        }   
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,351 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
0 comments No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,621 Reputation points
    2020-12-17T07:50:47.287+00:00

    I will show you how to navigate records by clicking Next and Previous, below is my code for you to implement it:

    Part1: Add two Buttons in xaml:

    <Button Name="btnPre" Width="120" Height="30" Content="Previous" Click="btn_Click"></Button>  
    <Button Name="btnNext" Width="120" Height="30" Content="Next" Click="btn_Click"></Button>  
    

    Part 2: The code for btn_Click

     private void btn_Click(object sender, RoutedEventArgs e)  
            {  
                int selectedIndex = 0;  
                if(dataGrid.SelectedIndex > 0)  
                {  
                    selectedIndex = dataGrid.SelectedIndex;  
                }  
                string strContent = (sender as Button).Content.ToString();  
      
                if (strContent == "Previous" && selectedIndex>0)  
                {  
                    dataGrid.SelectedIndex = selectedIndex-1;  
                    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex - 1);  
                    row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));  
                }  
                else if (strContent == "Next" && selectedIndex <dataGrid.Items.Count-1)  
                {  
                    dataGrid.SelectedIndex = selectedIndex +1;  
                    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex + 1);  
                    row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));  
                }    
            }  
    

    By the way, could you give me more description for your controls to change values correspondingly to the datagrid highlighter? How do you want to change the value?


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful