question

DPlug-8137 avatar image
0 Votes"
DPlug-8137 asked DPlug-8137 commented

How to populate datagrid and controls together

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");
         }   
sql-server-generaldotnet-csharpwindows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

DaisyTian-1203 avatar image
0 Votes"
DaisyTian-1203 answered DPlug-8137 commented

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.

· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes I want to change the values if the controls and the datagrid row selector moves from one record to another, I want the records to also change in the controls. Example if the row selector in the datagrid move from Record with Id of 1 to 2,the texbox control with Id should display 2 also. The same with the rest of the controls. Please I need help and also please check my previous code to see if I am correct with pulling data from the database to the controls. Thank you.

0 Votes 0 ·

Please someone should help me look at the code, my controls are not populated with data from the database, only the grid is populated. Somebody help me please. I am stranded. The code is in the post.

0 Votes 0 ·

@DPlug-8137
I'm a little confused by the code in your first if statement, do you want to show Student when some item in DGAll is selected?


0 Votes 0 ·

No, I want to pull the data out of the database. That's why I bind the controls to the fields in the database table using the sqlreader object. The controls are not populated with the data from he database, it's only the datagrid that gets populated with data from the database.

0 Votes 0 ·