Mise à jour de la firebase database à l’aide de Datagridview

Je peux append, éditer, supprimer une firebase database en utilisant listbox. Mais je veux le faire en utilisant DatagridView, je le lie déjà à ma firebase database.

Comment append, éditer, supprimer, mettre à jour ma firebase database dans datagridview en utilisant des codes?

Ce sont mes codes:

namespace Icabales.Homer { public partial class Form1 : Form { SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\homer\documents\visual studio 2010\Projects\Icabales.Homer\Icabales.Homer\Database1.mdf;Integrated Security=True;User Instance=True"); SqlCommand cmd = new SqlCommand(); SqlDataReader dr; SqlDataAdapter da; DataTable dt = new DataTable(); public Form1() { InitializeComponent(); } private void bindgrid() { ssortingng command = "select * from info"; da = new SqlDataAdapter(command, cn); da.Fill(dt); dataGridView1.DataSource = dt; } private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'database1DataSet.info' table. You can move, or remove it, as needed. this.infoTableAdapter.Fill(this.database1DataSet.info); cmd.Connection = cn; loadlist(); bindgrid(); } private void button1_Click(object sender, EventArgs e) { if (txtid.Text != "" & txtname.Text != "") { cn.Open(); cmd.CommandText = "insert into info (id,name) values ('" + txtid.Text + "' , '" + txtname.Text + "')"; cmd.ExecuteNonQuery(); cmd.Clone(); MessageBox.Show("Record Inserted"); cn.Close(); txtid.Text = ""; txtname.Text = ""; loadlist(); } } private void loadlist() { listBox1.Items.Clear(); listBox2.Items.Clear(); cn.Open(); cmd.CommandText = "select * from info"; dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { listBox1.Items.Add(dr[0].ToSsortingng()); listBox2.Items.Add(dr[1].ToSsortingng()); } } cn.Close(); } private void listBox2_SelectedIndexChanged(object sender, EventArgs e) { ListBox l = sender as ListBox; if (l.SelectedIndex != -1) { listBox1.SelectedIndex = l.SelectedIndex; listBox2.SelectedIndex = l.SelectedIndex; txtid.Text = listBox1.SelectedItem.ToSsortingng(); txtname.Text = listBox2.SelectedItem.ToSsortingng(); } } private void button2_Click(object sender, EventArgs e) { if (txtid.Text != "" & txtname.Text != "") { cn.Open(); cmd.CommandText = "delete from info where id = '"+txtid.Text+"'and name = '"+txtname.Text+"'"; cmd.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Record Deleted"); loadlist(); txtid.Text = ""; txtname.Text = ""; } } private void button3_Click(object sender, EventArgs e) { if (txtid.Text != "" & txtname.Text != "" & listBox1.SelectedIndex != -1) { cn.Open(); cmd.CommandText = "update info set id='"+txtid.Text+"',name='"+txtname.Text+"'where id='"+listBox1.SelectedItem.ToSsortingng()+"' and name='"+listBox2.SelectedItem.ToSsortingng()+"'"; cmd.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Record Updated"); loadlist(); txtid.Text = ""; txtname.Text = ""; } } } 

}

J’ai un dataGridView et un bouton sur un formulaire. Lorsque je modifie, insère ou supprime dans le dataGridView1, le code ci-dessous fait la magie

 public partial class EditPermit : Form { OleDbCommand command; OleDbDataAdapter da; private BindingSource bindingSource = null; private OleDbCommandBuilder oleCommandBuilder = null; DataTable dataTable = new DataTable(); public EditPermit() { InitializeComponent(); } private void EditPermitPermit_Load(object sender, EventArgs e) { DataBind(); } private void btnSv_Click(object sender, EventArgs e) { dataGridView1.EndEdit(); //very important step da.Update(dataTable); MessageBox.Show("Updated"); DataBind(); } private void DataBind() { dataGridView1.DataSource = null; dataTable.Clear(); Ssortingng connectionSsortingng = MainWindow.GetConnectionSsortingng(); //use your connection ssortingng please Ssortingng querySsortingng1 = "SELECT * FROM TblPermitType"; // Use your table please OleDbConnection connection = new OleDbConnection(connectionSsortingng); connection.Open(); OleDbCommand command = connection.CreateCommand(); command.CommandText = querySsortingng1; try { da = new OleDbDataAdapter(querySsortingng1, connection); oleCommandBuilder = new OleDbCommandBuilder(da); da.Fill(dataTable); bindingSource = new BindingSource { DataSource = dataTable }; dataGridView1.DataSource = bindingSource; } catch (Exception ex) { MessageBox.Show(ex.ToSsortingng(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 

J’ai le même genre de projet à la maison, je n’ai pas le code source avec moi mais si besoin je peux vérifier quelque part ce week-end pour voir ce que j’ai fait exactement, mais je crois que c’est un des cas suivants:

Comme vous utilisez un dataset et un dataadapter dataset , cela peut être réalisé très facilement.

Tant que votre propriété DataGridView1 a les propriétés activées pour que les utilisateurs puissent append / supprimer / modifier des lignes, vous pouvez utiliser le code suivant.

 DataAdapter.Update(DataTable); //in your code this would be: da.Update(dt); 

La DataAdapter.Update() générera automatiquement les commandes d’insertion / mise à jour / suppression nécessaires pour mettre à jour les résultats de votre requête de remplissage par rapport aux données actuelles de votre vue datagridview .
Vous pouvez également définir ces commandes (propriétés) si vous préférez les modifier, bien que cela ne soit pas nécessaire.

Cela ne fonctionne bien entendu qu’après qu’un utilisateur a apporté des modifications à DataGridView . Ajoutez ce code à un simple bouton et voyez si vous avez de la chance. C’était vraiment quelque chose d’aussi simple 🙂

J’ai implémenté une solution qui insère / met à jour / supprime des données dans la firebase database MS SQL directement à partir de DataGridView. Pour ce faire, j’ai utilisé les événements suivants: RowValidating et UserDeletingRow.

Il est supposé que vous avez

 SqlConnection _conn; 

déclarée et initialisée. Voici le code:

  private void dgv_RowValidating( object sender, DataGridViewCellCancelEventArgs e ) { try { if (!dgv.IsCurrentRowDirty) return; ssortingng query = GetInsertOrUpdateSql(e); if (_conn.State != ConnectionState.Open) _conn.Open(); var cmd = new SqlCommand( query, _conn ); cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning ); } } public ssortingng GetInsertOrUpdateSql( DataGridViewCellCancelEventArgs e ) { DataGridViewRow row = dgv.Rows[e.RowIndex]; int id = 0; int.TryParse( row.Cells["Id"].Value.ToSsortingng(), out id ); DateTime dob; DateTime.TryParse( row.Cells["Dob"].Value.ToSsortingng(), out dob ); ssortingng email = row.Cells["Email"].Value.ToSsortingng(); ssortingng phone = row.Cells["Phone"].Value.ToSsortingng(); ssortingng fio = row.Cells["Fio"].Value.ToSsortingng(); if (id == 0) return ssortingng.Format( "insert into {0} Values ('{1}','{2}','{3}','{4}')", "dbo.People", fio, dob.ToSsortingng( "dd-MM-yyyy" ), email, phone ); else return ssortingng.Format( "update {0} set Fio='{1}', Dob='{2}', Email='{3}', Phone='{4}' WHERE Id={5}", "dbo.People", fio, dob.ToSsortingng( "dd-MM-yyyy" ), email, phone, id ); } private void dgv_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e ) { try { int id = 0; int.TryParse( e.Row.Cells["Id"].Value.ToSsortingng(), out id ); ssortingng query = ssortingng.Format( "DELETE FROM {0} WHERE Id = {1}", "dbo.People", id ); var cmd = new SqlCommand( query, _conn ); if (_conn.State != ConnectionState.Open) _conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning ); } } 

J’espère que cela t’aides.