K
K
Kiram2019-09-11 07:38:13
Database
Kiram, 2019-09-11 07:38:13

How to update/delete/insert data into the database?

Good afternoon everyone. Implemented a connection to the database and output to the DataGridView. In this form:

private void Form1_Load(object sender, EventArgs e)
{
    // **Шаг 1: открываем соединение с базой данных DBNAME на сервере SQL с именем DBMSName**                            
    SqlConnection cn = new SqlConnection("Data Source=DBMSName;Initial Catalog=DBNAME;Persist Security Info=True;User ID=sa;Password=123");
    cn.Open();
    // **Шаг 2: Создаем SqlDataAdapter при помощи команды SELECT**            
    string strQuery;
    strQuery = "SELECT * FROM table1";
    SqlDataAdapter dAdapt = new SqlDataAdapter(strQuery, cn);
    // **Шаг З: Создаем и заполняем объект DataSet, а потом закрываем соединение**
    DataSet ds = new DataSet(); //создание DataSet (данные БД в памяти)
    DataTable dt = new DataTable(); //создание DataTable (таблица из БД в памяти)
    BindingSource bs = new BindingSource(); //
    try
    {
      dAdapt.Fill(ds, "TableName");
      dt = ds.Tables["TableName"];
      bs.DataSource = dt;
      DataGridView1.DataSource = bs;
      bindingNavigator1.BindingSource = bs;
    }
    catch (Exception ex)
    {
      //вывод ошибки
      MessageBox.Show(ex.Message);
    }
    finally
    {
      //закрытие подключения
      cn.Close();
    }
}

How to update/insert/delete data in the database after editing the data in the DataGridView and pressing the "Save" button? Can UpdateAll be used in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
idShura, 2019-09-11
@Kiram

you need to create UpdateCommand, InsertCommand and DeleteCommand
for SqlDataAdapter You can read it here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question