简体   繁体   中英

Save edits from DataGridView to Datatable

Hi i want to save edits in DataGriView to datatable , i tried that code but an error shows 'System.ArgumentOutOfRangeException: 'The index was out of range. It must not be negative and must be smaller than the size of the collection. Parameter name: index '' help

private void button11_Click(object sender, EventArgs e)
    {
        con.Open();

        String query = "SELECT * FROM Taom";

        SqlDataAdapter SDA = new SqlDataAdapter(query, con);
        DataTable dt1 = new DataTable();

        DataSet ds1 = new DataSet();
        DataTable dt = new DataTable();
        dataGridView1.DataSource = dt1;
        SDA.Fill(dt);
        dataGridView1.Rows[2].Cells[2].Value = Math.Atan((Convert.ToDouble(dataGridView1.Rows[5].Cells[2].Value)) / (Convert.ToDouble(dataGridView1.Rows[6].Cells[2].Value)));
        dataGridView1.Rows[3].Cells[2].Value = Math.Atan((Convert.ToDouble(dataGridView1.Rows[7].Cells[2].Value)) / (Convert.ToDouble(dataGridView1.Rows[8].Cells[2].Value)));
        ds1.Tables.Add(dt);
con.Close();}

I changed my code to that code no errors showed after i run values on datagridview change but no changes in datatable !!!

string query = "SELECT * FROM [dbo].[Taom]";
        SqlConnection conn = new SqlConnection(@"Data Source=STE-P0024818PW;Initial Catalog=test;Integrated Security=True");
        conn.Open();

        SqlDataAdapter SDA = new SqlDataAdapter(query, conn);
        DataSet ds1 = new DataSet();
        DataTable dt = new DataTable();
        SDA.Fill(dt);
        dt.Rows[0]["Contents"] = "98"; //Before it was 10
        dt.Rows[1]["Contents"] = "99"; //Before it was 11
        ds1.Tables.Add(dt);

        conn.Close();

Fill the right value inside your table and after pass the table rightly filled in your datasource, don't change this directly in the gridview like:

I try myself and it works:

private void Run()
{
    string query = "SELECT * FROM dbo.[Anrufthema]";
    SqlConnection conn = new SqlConnection("MyConnectionString");
    conn.Open();

    SqlDataAdapter SDA = new SqlDataAdapter(query, conn);
    DataSet ds1 = new DataSet();
    DataTable dt = new DataTable();
    SDA.Fill(dt);
    dt.Rows[0]["Anrufthema"] = "98"; //Before it was 10
    dt.Rows[1]["Anrufthema"] = "99"; //Before it was 11
    ds1.Tables.Add(dt);

    conn.Close();
}

My Result, it works !

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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