-1

i am creating a simple crud in c#.net.after add the record record will show on the datagridview itself. but i couldn't do it. code which tried so far i attched below.

code

sql = "insert into student(stname,course,fee)values(@stname,@course,@fee)";
con.Open();
cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@stname", stname);
cmd.Parameters.AddWithValue("@course", course);
cmd.Parameters.AddWithValue("@fee",stfee);
load();

dataGridView1.Update();
dataGridView1.Refresh();

data load to datagridview

public void load()
{
   try
   {
       string sql;
       sql = "select * from student";
       cmd = new SqlCommand(sql, con);
       con.Open();
       dr = cmd.ExecuteReader();
       dee = new SqlDataAdapter(sql, con);

       while (dr.Read())
       {
           dataGridView1.Rows.Add(dr[0], dr[1], dr[2], dr[3]);

       }
       con.Close();
   }
   catch(Exception ex)
   {

   }
   finally
   {
     con.Close();
     cmd.Dispose();      
  }    
}
jaya priya
  • 75
  • 8
  • 1
    Quick notes: The first code block, you are not executing anything, so why open the connection and command? Use `using` statements to dispose of objects you no longer need. Don't use `AddWithValue`, use `Add` and specify the data type. Specifically you need to execute the first code block to insert the data and *then* do another to fetch it. – Trevor Oct 08 '19 at 12:54
  • https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ – Sean Lange Oct 08 '19 at 13:19
  • And never ever ever use an empty catch. That is an antipattern I call try/squelch. Nothing worse than catching an error and then just treating it like nothing happened. – Sean Lange Oct 08 '19 at 13:21

2 Answers2

0

I think you just need to execute the query, the insert instruction only opens the connection !!!

 sql = "insert into student(stname,course,fee)values(@stname,@course,@fee)";
    con.Open();
    cmd = new SqlCommand(sql, con);
    cmd.Parameters.AddWithValue("@stname", stname);
    cmd.Parameters.AddWithValue("@course", course);
    cmd.Parameters.AddWithValue("@fee",stfee);

    **int isexist;
    isexist = Convert.ToInt32(sCommand.ExecuteScalar());
    if(isexist > 0)
    {...**

    load();

    dataGridView1.Update();
    dataGridView1.Refresh();

Ahmed Msaouri
  • 316
  • 1
  • 10
0

Using SqlDataAdapter:

...
dee = new SqlDataAdapter(sql, con);
Dataset dataset = new Dataset();
dee.Fill(dataset);
dataGridView1.ItemSource = dataset.Tables[0];
..
apomene
  • 14,282
  • 9
  • 46
  • 72