【问题标题】:Inserting a row in database from DataGridview and Textfield从 DataGridview 和 Textfield 在数据库中插入一行
【发布时间】:2015-02-18 08:03:52
【问题描述】:

我的问题是,我想从 DataGridview 和一个文本框将数据保存在数据库中。这是我的示例代码:

            connect.ConnectionString = coo;
            connect.Open();
            string str = string.Concat("insert into Sales values('", (1st column item in the datagridview), "','", textBox2.Text, "','", textBox3.Text, "','", textBox4.Text, "');");
            command = new OleDbCommand(str, connect);
            command.ExecuteNonQuery();
            command.Connection = connect;
            connect.Close();

请提供指导。

【问题讨论】:

    标签: c# winforms datagridview save


    【解决方案1】:

    将 datGridView 所有行插入数据库:

    我们知道将值从文本框和其他数据输入控件插入数据库 但是从 dataGridView 输入到数据库的值与这些方式略有不同 因为在这里我们必须将 dataGridView 中包含的所有行插入到数据库中。 单击此处将值从文本框插入到 datagridview 控件。所以对于我们 必须运行一个循环来收集数据库中所有行的所有数据。

    事件:引发此代码的事件是 saveButton_Click

    OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\naresh\My stuff\Thal tre tsks trim\Thalassemia\Data\thalsemia.accdb");
    con.Open();
    
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    
    {
    
       OleDbCommand cmd= new OleDbCommand("INSERT INTO table1(name,number,salory,) VALUES
     ('"+dataGridView1.Rows[i].Cells["Column1"].Value+"','"+dataGridView1.Rows[i].Cells["Column2"].Value+"',
    '"+dataGridView1.Rows[i].Cells["Column3"].Value+" ' ",con);
    
       cmd.ExecuteNonQuery();
    
    }
    
    con.Close();
    

    希望这段代码对你有所帮助。

    【讨论】:

    • 这是我要找的代码!!这个 "+dataGridView1.Row[i].Cells["Column1"].Value+" 和我扩展了一些 texbox1.text 到它。谢谢你,先生。它对我有很大帮助!!
    • 我觉得它有帮助,那么请给它点赞吧!Spidey Eudz Aragon
    【解决方案2】:

    要获取您可以使用的选定单元格值:

    string Selection;
    if (dataGridView1.SelectedRows.Count != 0)
    {
        DataGridViewRow row = this.dataGridView1.SelectedRows[0];
        Selection=row.Cells[0].Value.ToString();
    }
    

    将它们添加到您的查询使用参数中:

    string query = "insert into Sales values(@param1,@param2,@param3,@param4)");
    command = new OleDbCommand(query, connect);
    command.Parameters.AddWithValue("@param1", Selection);
    command.Parameters.AddWithValue("@param2", textBox2.Text);
    command.Parameters.AddWithValue("@param3", textBox3.Text);
    command.Parameters.AddWithValue("@param4", textBox4.Text);
    command.ExecuteNonQuery();
    command.Connection = connect;
    connect.Close();
    

    【讨论】:

      【解决方案3】:

      我会给你一些指导方针,但不会提供你的完整代码:

      您需要在网格视图中添加一个新列,并在其中放置一个按钮/链接按钮作为“编辑/保存/存储”或您想要的任何内容。

      当用户单击该按钮时,应触发 Gridview 的 ItemCommand 事件,您必须在其中获取所选行的索引,例如 e.Rowindex(您可以查看 google 以获取有关此的详细教程),并且一旦您有了索引,这就是您需要的想法。在这种情况下,您应该将此数据保存在数据库中。

      【讨论】:

        猜你喜欢
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 2012-08-09
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2017-03-29
        • 1970-01-01
        相关资源
        最近更新 更多