0

I have a datagridview in which I display informations from my database.
I want my user to add information in the last row and then he will click on the button add that will add a new row into the database.
The function is below. When I debug it, it goes through all my rows, get all the informations, but it doesn't add my new row to the database.

private void addNewAgent()
{
    int row = 0;

    if (ViewState["CurrentTable"] !=null)
    {
        DataTable mydt = (DataTable)ViewState["CurrentTable"];
        DataRow myrow = null;            

        if (mydt.Rows.Count>0)
        {
            for (int i = 1; i <= mydt.Rows.Count; i++)
            {

                TextBox fn = GridView1.Rows[row].Cells[1].FindControl("txt_FirstName") as TextBox;
                TextBox ln = GridView1.Rows[row].Cells[2].FindControl("txt_LastName") as TextBox;
                TextBox email = GridView1.Rows[row].Cells[3].FindControl("txt_Email") as TextBox;

                myrow = mydt.NewRow();
                myrow["UserID"] = i + 1;
                mydt.Rows[i - 1]["FirstName"] = fn.Text;
                mydt.Rows[i - 1]["LastName"] = ln.Text;
                mydt.Rows[i - 1]["email"] = email.Text;

                row++;                   
            }
            mydt.Rows.Add(myrow);                
            ViewState["CurrentTable"] = mydt;
            GridView1.DataSource = mydt;
            GridView1.DataBind();             
        }
        else
        {
            Response.Write("view state is null"); 
        }
    }

}

1 Answers1

0

You are missing the code to persist the data in the database. Right now, you are just adding the gridview data into a viewstate datatable. I don't see the point of doing that, as the gridview itself already maintain its data in viewstate.

imho, you should load the data in the gridview on page load catch the gridview rowcommands (edit, update, delete) to update the database.

You will easily find samples online how to manage data through a gridview here is one http://asp.net-informations.com/gridview/gridview-operations.htm

If you have specific reasons not to persists the data immediately on edit, you could add a button "Update DB" that would loop through all records in your viewstate datatable, and explicitely update the relared database records

Luc Debliquis
  • 304
  • 1
  • 6
  • but by doing that: mydt.Rows.Add(myrow); i am adding to my table no? I then usually use my commandbuilder – NewPassionnate Dec 04 '16 at 21:31
  • 1
    your datatable is disconnected from the database (in memory), to persist its changes, you need to specifically call a command or logic (using a sqldataadapter for example) see http://stackoverflow.com/questions/7055799/how-to-save-the-dataset-after-making-changes-to-the-database – Luc Debliquis Dec 04 '16 at 21:35