Link to home
Start Free TrialLog in
Avatar of oana d
oana d

asked on

Why is my datagridview not updating the values?WINFORMS

Hello,I have a project in winforms which takes care of the attendance of the students.In my project I have a form called AttendanceList which has the following:
-a textbox for the Serial number on the NFC tag( the attendance will be based on every student swiping the card over the card reader).
-a combobox where the teacher selects the Course and based on the course,when the teacher clicks a button,the list with all the students should appear.
- a datagridview which displays,updates and deletes the students.
The problem that i'm facing is that when a student registers,he will appear in table RegisterStudent(which is the table for all the registered students).I want to take the values from RegisterStudent(sNr,SN,fName and lName) and insert it in AttendanceList table.This is my method in doing so:
  private void LoadStudents()
        {
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        string query = "insert into AttendanceList(SN,sNr,fName,lName) select SN, sNr, fName,lName from RegisterStudent p inner join StudentCourses c on p.SN=c.StudentId WHERE  c.CourseId = '" + cmbClassId.SelectedValue.ToString() + "'";
                      // cmd.Parameters.AddWithValue("@CourseId", cmbClassId.Text);
                        cmd.Parameters.AddWithValue("@SN", txtStudentId.Text);
                        cmd.Connection = conn;
                        conn.Open();
                        dr = cmd.ExecuteReader();
                        if(dr.HasRows==true)
                        {
                            while(dr.Read())
                            {
                                if(dr.HasRows==true)
                                {
                                    cmd.Parameters.AddWithValue("@fName", dr["fName"].ToString());
                                    cmd.Parameters.AddWithValue("@lName", dr["lName"].ToString());
                                    cmd.Parameters.AddWithValue("@sNr", dr["sNr"].ToString());
                                }
                            }
                        }
                       
                        dr.Close();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                        dg.Update();
                        dg.Refresh();

                        LoadData();
                        Clr();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
               
            }

        }
When i call this method and i look into sql server,i can see that the values are inserted,in exchange the datagridview won't update with the new values.Also,I have the error "ExecuteReader:CommandText property has not been initialized".User generated imageUser generated imageWhen I click on the button to call this method i also get an error for duplicate key since i'm trying to insert the values again.This is my AttendanceList table:
CREATE TABLE [dbo].[AttendanceList](
      [sNr] [int]  NOT NULL,
      [SN] [char](10) NOT NULL,
      [fName] [nvarchar](max) NOT NULL,
      [lName] [nvarchar](max) NOT NULL,
      [dateArrival] [datetime] NULL,
      [dateDeparture] [datetime] NULL,
      [Attending] [bit] NULL,
      [CourseID] [nvarchar](50) NULL,
      [Departed] [bit] NULL,
PRIMARY KEY CLUSTERED
(
      [SN] ASC
 

and this is my RegisterStudent table:
CREATE TABLE [dbo].[RegisterStudent](
      [SN] [char](10) NOT NULL,
      [sNr] [int] NOT NULL,
      [fName] [nvarchar](max) NOT NULL,
      [lName] [nvarchar](max) NOT NULL,
      
PRIMARY KEY CLUSTERED
(
      [SN] ASC

I also use this method every time to load data,and since there is data into the database,i don't understand why none of it works:
 private void LoadData()
        {

         
            string str = "select * from AttendanceList where courseid='" + cmbClassId.SelectedValue.ToString() + "'";
            da = new SqlDataAdapter(str, connstr);
            ds = new DataSet();
            da.Fill(ds);
            dt = ds.Tables[0];
            bi.DataSource = dt;
            dg.DataSource = bi;
            dg.ClearSelection();
            txtStudentId.Focus();
            var count = Convert.ToInt32(dg.Rows.Count.ToString()) - 1;
            txtCount.Text = count.ToString();
        }

Can someone please help me in this matter?Thank you in advance and please let me know if i can provide anything else.I mention that I have tried to look over to see why is not working and i have modified the method since it previously looked like this:
 private void LoadStudents()
        {
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        string query = "select SN, sNr, fName,lName from RegisterStudent p inner join StudentCourses c on p.SN=c.StudentId WHERE  c.CourseId = '" + cmbClassId.SelectedValue.ToString() + "'";
   da = new SqlDataAdapter(str, connstr);
            ds = new DataSet();
            da.Fill(ds);
            dt = ds.Tables[0];
            bi.DataSource = dt;
            dg.DataSource = bi;
            dg.ClearSelection();
            dg.Refresh();
            dg.Update();
            txtStudentId.Focus();

It worked giving me what i wanted,by displaying all the students from RegisterStudent who signed up for that specific course but it didn't insert it into AttendanceList .How can I make it so that it will insert it into AttendanceList and at the same time update the datagridview so that I can see the values in it?
Avatar of Max Destiny
Max Destiny
Flag of United States of America image

why dont you try to save the data into a file for example:

for saving:
string[]student1 = new string[3];

student1.SetValue(0,studentname);

student1.SetValue(1,class);

student1.SetValue(2,attendtance);

stringi = string.Join(student1,'/');

List<string>arraylist = new List<string[]>();

arraylist.Add(stringi);

File.WriteLines("savingdocument1",arraylist.ToArray());

//C#//

Open in new window


for loading:

foreach(var line in File.ReadLines("savingdocument1"))
{
var array = line.Split("/");

datagridview1.AddRow(array);


}

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.