Here is my code :
public partial class Form1 : Form
{
SqlCommandBuilder cmbl;
string con = \"Data Source=localhost;Initial Catalog=db;Persist Security In
You should bind the DataGridView
to DataTable
, then when you change a cell value or add or remove rows, the changes apply on DataTable
. Then you can save data table changes using a TableAdapter
:
this.dataGridView1.DataSource = dataTable;
Note: To store true/false
or Yes/No
values, it's better to use bit
data type in sql server. But in the below example I supposed you need to store values as Y/N
as nvarchar(50)
and I setup a DataGridViewCheckBoxColumn
to support editing a string column.
Example
Suppose we have a table Table1
:
Column1: int, primary key
Column2: nvarchar(50), Allows Null, Containing Y or N as vaule
And we want to edit data of Table1
in a DataGridView
:
Here is the code you can use to load and edit and save data:
private DataTable table;
private SqlDataAdapter dataAdapter;
private void sampleForm_Load(object sender, EventArgs e)
{
var command = "SELECT * FROM Table1";
var connection = @"Your connection string";
table = new DataTable();
dataAdapter = new SqlDataAdapter(command, connection);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(table);
//Set false as default value for Column2
table.Columns["Column2"].DefaultValue = false;
var column1 = new DataGridViewTextBoxColumn();
column1.Name = "Column1";
column1.DataPropertyName = "Column1";
var column2 = new DataGridViewCheckBoxColumn();
column2.Name = "Column2";
column2.DataPropertyName = "Column2";
column2.TrueValue = "Y";
column2.FalseValue = "N";
this.dataGridView1.Columns.Add(column1);
this.dataGridView1.Columns.Add(column2);
//Bind grid to table
this.dataGridView1.DataSource = table;
}
private void saveButton_Click(object sender, EventArgs e)
{
//Save data
this.dataGridView1.EndEdit();
dataAdapter.Update(table);
}