2012-12-28 131 views
1

我可以使用listbox添加,編輯和刪除數據庫。但我想用DatagridView來做,我已經將它綁定到了我的數據庫。使用Datagridview更新數據庫

如何使用代碼在datagridview中添加,編輯,刪除更新我的數據庫?

這是我的代碼:

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() 
    { 
     string 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].ToString()); 
       listBox2.Items.Add(dr[1].ToString()); 
      } 
     } 
     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.ToString(); 
      txtname.Text = listBox2.SelectedItem.ToString(); 
     } 

    } 

    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.ToString()+"' and name='"+listBox2.SelectedItem.ToString()+"'"; 
      cmd.ExecuteNonQuery(); 
      cn.Close(); 
      MessageBox.Show("Record Updated"); 
      loadlist(); 
      txtid.Text = ""; 
      txtname.Text = ""; 
     } 
    } 
} 

}

回答

0

我有同樣的項目在家裏,我沒有與我的源代碼,但如果需要,我可以檢查本週末的某個地方,看看我做了什麼,但我相信這是一些fol降低:

由於您使用的是datasetdataadapter,因此可以非常輕鬆地實現。

只要你的DataGridView1有啓用用戶添加/刪除/編輯行的屬性,你可以使用下面的代碼。

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

DataAdapter.Update()方法將自動生成任何插入/更新/刪除更新您填寫的查詢與您datagridview當前數據進行比較的結果所需要的命令。
你也可以設置這些命令(屬性)以防萬一你喜歡修改它們,雖然這不是必需的。

這隻有在用戶對DataGridView進行更改後纔會起作用。將此代碼添加到一個簡單的按鈕,看看你是否有任何運氣。它確實是這樣簡單的:)

+0

我該在哪裏輸入密碼? – HOmer

+0

@例如,您可以將其添加到'button_click'事件中。 – AssaultingCuccos

+0

我如何使用它?我可以把它放在方法加載列表上嗎? – HOmer

1

我有一個dataGridView和一個窗體上的按鈕。當我做任何編輯,插入或缺失在dataGridView1,下面的代碼做魔

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(); 

     String connectionString = MainWindow.GetConnectionString(); //use your connection string please 
     String queryString1 = "SELECT * FROM TblPermitType"; // Use your table please 

     OleDbConnection connection = new OleDbConnection(connectionString); 
     connection.Open(); 
     OleDbCommand command = connection.CreateCommand(); 
     command.CommandText = queryString1; 
     try 
     { 
      da = new OleDbDataAdapter(queryString1, connection); 
      oleCommandBuilder = new OleDbCommandBuilder(da); 
      da.Fill(dataTable); 
      bindingSource = new BindingSource { DataSource = dataTable }; 
      dataGridView1.DataSource = bindingSource; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 


    } 
0

我已經實現的是插入在直接MS SQL數據庫從DataGridView /更新/刪除數據的解決方案。 爲了實現這一點,我使用了以下事件:RowValidating和UserDeletingRow。

據推測,你有

SqlConnection _conn; 

聲明並初始化。 這裏是代碼:

private void dgv_RowValidating(object sender, DataGridViewCellCancelEventArgs e) 
    { 
     try 
     { 
      if (!dgv.IsCurrentRowDirty) 
       return; 

      string 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 string GetInsertOrUpdateSql(DataGridViewCellCancelEventArgs e) 
    { 
     DataGridViewRow row = dgv.Rows[e.RowIndex]; 
     int id = 0; 
     int.TryParse(row.Cells["Id"].Value.ToString(), out id); 

     DateTime dob; 
     DateTime.TryParse(row.Cells["Dob"].Value.ToString(), out dob); 

     string email = row.Cells["Email"].Value.ToString(); 
     string phone = row.Cells["Phone"].Value.ToString(); 
     string fio = row.Cells["Fio"].Value.ToString(); 

     if (id == 0) 
      return string.Format("insert into {0} Values ('{1}','{2}','{3}','{4}')", "dbo.People", fio, dob.ToString("dd-MM-yyyy"), email, phone); 
     else 
      return string.Format("update {0} set Fio='{1}', Dob='{2}', Email='{3}', Phone='{4}' WHERE Id={5}", "dbo.People", fio, dob.ToString("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.ToString(), out id); 
      string query = string.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); 
     } 
    } 

希望這會有所幫助。