Ivan Climov

Ivan Climov

  • 1k
  • 692
  • 22.6k

How to save changes from “textbox” to database?

Nov 26 2018 2:21 AM
The current entry from "dataGridView1" is displayed in "textBox1".
The user in "textBox1" makes changes.
How to save changes from "textBox" to the database and display in "dataGridView1"?
I enclose the code of my decision.
If the form has several "textBox", "checkBox1", then make an event for each element, somehow troublesome ...
Are there any other more efficient ways to do this?
 
picture - http://www.imageup.ru/img249/3222168/2018-11-23_15-05-54.png.html
  1. public partial class Frm1UC : UserControl  
  2.     {  
  3.         DataTable dt;          
  4.    
  5.         OleDbConnection connection;  
  6.         OleDbDataAdapter adapter;  
  7.         OleDbCommandBuilder commandBuilder;  
  8.           
  9.    
  10.         static string catBD = @"c:\vs\csharp\db_GridVAccess.accdb";  
  11.         string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", catBD);  
  12.    
  13.         string sql = "SELECT * FROM TreeFolder_tbl";  
  14.    
  15.         // *** ???????????  
  16.         public Frm1UC()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.    
  21.         // *** ???????. ???????? ?????  
  22.         private void Frm1UC_Load(object sender, EventArgs e)  
  23.         {  
  24.             using (OleDbConnection cn = new OleDbConnection())  
  25.             {  
  26.                 connection = new OleDbConnection(connectionString);  
  27.                 connection.Open();  
  28.                                   
  29.                 adapter = new OleDbDataAdapter(sql, connection);  
  30.    
  31.                 commandBuilder = new OleDbCommandBuilder(adapter);  
  32.    
  33.                   
  34.                 dt = new DataTable();  
  35.                 adapter.Fill(dt);  
  36.                 dataGridView1.DataSource = dt;  
  37.             }  
  38.         }  
  39.    
  40.    
  41.         // ????? ??????  
  42.         private void dataGridView1_SelectionChanged(object sender, EventArgs e)  
  43.         {  
  44.             textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();  
  45.         }  
  46.    
  47.         // ???????. ????????? ??????  
  48.         private void textBox1_TextChanged(object sender, EventArgs e)  
  49.         {  
  50.             dataGridView1.CurrentRow.Cells[1].Value = textBox1.Text;  
  51.         }  
  52.    
  53.         // ?????????  
  54.         public void Save()  
  55.         {  
  56.             adapter.Update(dt);  
  57.         }  
  58.    
  59.         private void button1_Click(object sender, EventArgs e)  
  60.         {  
  61.             Save();  
  62.         }  
  63.    
  64.         
  65.     }  
 
 
 
 

Answers (3)