简体   繁体   English

函数未向我的数据库添加数据

[英]Function doesn't add data to my database

I have a datagridview in which I display informations from my database. 我有一个datagridview,其中显示来自数据库的信息。
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"); 
        }
    }

}

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. 现在,您只是将gridview数据添加到viewstate数据表中。 I don't see the point of doing that, as the gridview itself already maintain its data in viewstate. 我看不到这样做的意义,因为gridview本身已经将其数据保持在viewstate中。

imho, you should load the data in the gridview on page load catch the gridview rowcommands (edit, update, delete) to update the database. 恕我直言,您应该在页面加载时将数据加载到gridview中,然后捕获gridview row命令(编辑,更新,删除)以更新数据库。

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 您可以在网上轻松找到示例,如何通过gridview管理数据,这是一个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 如果您有特定的原因不希望在编辑时立即保留数据,则可以添加一个“更新数据库”按钮,该按钮将循环遍历视图状态数据表中的所有记录,并显式更新相关的数据库记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM