I\'m trying to insert new records into the source table from the C# interface grid view.... But when I retrieve the records with the buttonclick code shown below... Im getti
Code is using ExecuteNonQuery, it returns no of rows affected not the results your query returns.
Use ExecuteReader
instead.
var reader = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dtLoad(reader);
Is there any option or property for enabling the insertion option in the gridview
dataGridView1.ReadOnly = false;
dataGridView1.EditMode = DataGridViewEditMode.EditOnF2; //if you want to edit on F2.
To let the user add, delete or edit rows with DataGridView
:
To let the user save changes using a SqlDataAdapter:
DataSource
of DataGridView
Code
DataTable table;
SqlDataAdapter adapter;
private void Form1_Load(object sender, EventArgs e)
{
//Create adapter
var connection = @"your connection string";
var command = "SELECT * FROM Table1";
adapter = new SqlDataAdapter(command, connection);
//Create Insert, Update and Delete commands
var builder = new SqlCommandBuilder(adapter);
//Load data
table = new DataTable();
adapter.Fill(table);
//Bind the grid to data
this.dataGridView1.DataSource = table;
//Enable add, delete and edit
this.dataGridView1.AllowUserToAddRows = true;
this.dataGridView1.AllowUserToDeleteRows = true;
this.dataGridView1.ReadOnly = false;
}
private void saveButton_Click(object sender, EventArgs e)
{
//Save Data
adapter.Update(table);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
adapter.Dispose();
}
Note
ExecuteNonQuery
. You only need a connection string and a command text. Then you can create a data adapter. Then you even don't need to manage opening and closing the connection, data adapter manages it.SELECT TOP 1 *
, if you add data and save, you can't see updates next time you load the data because you load only a single record.