How to insert a new row into datagridview(bound to database)

Answered How to insert a new row into datagridview(bound to database)

All Replies

  • Sunday, May 06, 2012 3:28 AM
     
      Has Code

    Hi:)

    Yes I think so——If you bind the DataTable generated from a SqlDataAdapter to the DataGridView,and once you've added rows to the GridView,it will be also mapped to the real DataTable。But you should drag and drop a button and click to write the modified things into real table by using:

    SqlDataAdapter.Update(DataTable instance);

       QQ我:讨论(Talk)
    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处

  • Sunday, May 06, 2012 7:13 PM
     
     

    How to get the last row's cells?

    Row[x][y]....

    x=DataGridView1.Rows.Count-1?

  • Monday, May 07, 2012 1:32 AM
     
     

    How to get the last row's cells?

    Row[x][y]....

    x=DataGridView1.Rows.Count-1?

    Yes, I think you can do this:

    dataGridView1.Rows[DataGridView1.Rows.Count-1].Cells[Column Index].Value;

    Maybe the value is null (Nothing in Basic), and the row isn't mapped to the real DataTable as its DataSource of DataGridView.

    In my  mind,I suggest you set AllowUserToAdd=false,this means you cannot directly add data record through the DataGridView directly,and then you can use this.


       QQ我:讨论(Talk)
    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处

  • Monday, May 07, 2012 5:13 AM
    Moderator
     
     Answered Has Code

    The last row is:

    this.dataGridView1.Rows[this.dataGridView1.Rows.Count-2].Cells[0].Value

    And the new row is:

    this.dataGridView1.Rows[this.dataGridView1.Rows.Count-1].Cells[0].Value


    Mike Zhang[MSFT]
    MSDN Community Support | Feedback to us

  • Monday, May 07, 2012 12:46 PM
     
      Has Code

    It looks great. Can we use a loop to go through al cells?

    Right now I use

    DataRow dr = new DataRow();
    dr["column1"] = this.dataGridView1.Rows[this.dataGridView1.Rows.Count-2].Cells[0].Value;
    \\ can I use dr[0] something so we can use foreach..

  • Monday, May 07, 2012 1:53 PM
     
      Has Code

    ure:

    //define datatable (with all columns you want to have)...
    //then:
    DataRow dr;
    for(int i=0;i<dataGridView1.Rows.Count; i++)
    {
        dr = table.NewRow();
        dr[i] = dataGridView1[0, i].Value;
        dataTable.Rows.Add(dr);
    }



    Mitja


  • Monday, May 07, 2012 2:19 PM
     
      Has Code
    Enen. But I found it might be
    for(int i=0;i<dataGridView1.Columns.Count; i++)
    

  • Monday, May 07, 2012 2:30 PM
     
     Answered
    Depends. If you wanna loop Rows or Columns? Decide it by your self. I actually dont know, I cant read your mind.

    Mitja

    • Marked As Answer by ardmore Monday, May 07, 2012 2:39 PM
    •