C#-插入会话值和动态Gridview';s数据

本文关键字:数据 Gridview 动态 插入 会话 C#- | 更新日期: 2023-09-27 18:25:19

我找到了这段代码(归功于:http://www.c-sharpcorner.com/UploadFile/8c19e8/dynamically-adding-and-deleting-rows-in-gridview-and-saving/),其中动态创建Gridview。

我想在"p_deaseases"数据表中添加Session["pa_id"]以及gridview数据(使用参数)。该代码只插入网格视图数据效果很好,没有我添加的额外列"P_Id"。我在修改代码的地方做了一些评论。

尽管发生了变化,但仍然存在错误。

你能建议我换什么吗?

代码:

 private string GetConnectionString()
    {
        return ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
    }

    private void InsertRecords(StringCollection sc)
    {
        StringBuilder sb = new StringBuilder(string.Empty);
        string[] splitItems = null;
        const string sqlStatement = "INSERT INTO P_deasease (P_Id,Nosos,Situ,Year_d,Therapy) VALUES (@p_id)"; //I added the P_Id and the parameter
        int id = Convert.ToInt32(Session["pa_id"]); //I added that
        foreach (string item in sc)
        {
            if (item.Contains(","))
            {
                splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
            }
        }
        using (SqlConnection connection = new SqlConnection(GetConnectionString()))
        {
            connection.Open();

            using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
            {
                cmd.Parameters.AddWithValue("@p_id", id); //I added that
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
        }

        lblMessage.ForeColor = System.Drawing.Color.Green;
        lblMessage.Text = "Οι εγγραφές αποθηκεύτηκαν!";
    }

  protected void BtnSave_Click(object sender, EventArgs e)
    {
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the values  
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
                    //add them to the collections with a comma "," as the delimited values  
                    sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, ddl1.SelectedItem.Text, box3.Text));
                    rowIndex++;
                }
                //Call the method for executing inserts  
                InsertRecords(sc);
            }
        }
    }  

C#-插入会话值和动态Gridview';s数据

您添加参数的方式不对。注意foreach添加的字符串如下:

<already built sql expression> (s1,s2,s3,s4)

示例:

INSERT INTO P_deasease (Nosos,Situ,Year_d,Therapy) VALUES (s1,s2,s3,s4)

这是一个有效的插入子句。现在有了你的添加,这看起来像:

INSERT INTO P_deasease (P_Id,Nosos,Situ,Year_d,Therapy) VALUES (@p_id)(s1,s2,s3,s4)

这根本无效。

现在,您可能希望为所有新条目使用相同的值填充p_Id。这应该通过以下方式来完成:

    const string sqlStatement = "INSERT INTO P_deasease (P_Id,Nosos,Situ,Year_d,Therapy) VALUES "; //I added the P_Id and the parameter
    int id = Convert.ToInt32(Session["pa_id"]); //I added that
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}(@p_id, '{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
        }
    }

但说实话,这样做很奇怪。如果P_Id是主键列,则会失败,因为不能有两行具有相同的主键。您是否真的考虑过为数据库中的列设置自动生成ID?