mark333...333...333
mark333...333...333

Reputation: 1360

Alternative Ways In Adding New Rows in Datasource Data Grid View

I'm creating a project in C# windows form. What I'm trying to do is add new rows in the datasource data grid view. But the problem is, the error says that adding new rows can't add programmatically in the datasource data grid.

Here's my method in fetching the data and transfer it in the data grid view.

public DataTable GetData(ClassName classVar){
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = ...; // My connection string
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = ...; // My Query

    DataTable table = new DataTable();
    table = ...ExeReader(cmd);
    return table;
}

The Codes inside my form

DataTable getDataTable;
getDataTable = ClassQuery.GetData(classVar);
dgv_details.DataSource = getDataTable;

And this is my add button

dgv_details.Rows.Add(txtBox1.Text,txtBox2.Text);

What are the alternative ways in adding data inside the datasourced datagridview? Thanks in advance.

Upvotes: 0

Views: 673

Answers (1)

sowjanya attaluri
sowjanya attaluri

Reputation: 911

Try the below code. First add row to datatable and then bind that table to datagridview.

  DataRow dr = datatable1.NewRow();
  dr[0] = "HAI"; // add data in first column of row
  datatable1.Rows.InsertAt(dr, 0); // insert new row at position zero
  datatable1.Rows.Add(dr); // addnew row at last 

Upvotes: 1

Related Questions