2016-04-22 76 views
-1

我想在網頁上實現一個按鈕,該按鈕將刪除gridview上顯示的所有數據。有沒有更簡單的方法來使用按鈕一次刪除所有數據?從gridview中刪除所有數據

+0

並不是說你發佈的代碼量有多大關係,但VS2015是'IDE',而不是'Framework'版本。 –

+0

我已經刪除了Visual Studio 2015標籤,因爲此問題與編碼相關,並不是特定於VS. –

+0

我們需要你的代碼。我們如何知道是否有更簡單的方法來做事情,如果你沒有發佈代碼來比較它? – Matthew

回答

1

這樣做很簡單。只需遍歷GridView中的每一行並獲取主鍵值,然後使用sql查詢從數據庫中刪除記錄。 這裏的代碼可以幫助你。我正在使用NorthWind示例數據庫。

void loaddata() 
    { 
     SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabaseConnectionString"].ConnectionString); 
     SqlCommand command = new SqlCommand(); 
     connection.Open(); 
     try 
     { 
      command = connection.CreateCommand(); 
      command.CommandText = "SELECT * FROM Employees"; 
      SqlDataAdapter adapter = new SqlDataAdapter(command); 
      DataTable datatable = new DataTable(); 
      adapter.Fill(datatable); 
      GridView1.DataSource = datatable; 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
     finally 
     { 
      if (connection.State == ConnectionState.Open) 
      { 
       connection.Close(); 
      } 
     } 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     int employee_id; 

     SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabaseConnectionString"].ConnectionString); 
     SqlCommand command = new SqlCommand(); 
     connection.Open(); 
     try 
     { 
      command = connection.CreateCommand(); 
      for (int i = 0; i < GridView1.Rows.Count; i++) 
      { 
       employee_id = Convert.ToInt32(GridView1.Rows[i].Cells[0].Text); 
       command.CommandText = "DELETE FROM Employees WHERE EmployeeID = '" + employee_id + "'"; 
       command.ExecuteNonQuery(); 
      } 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
     finally 
     { 
      if (connection.State == ConnectionState.Open) 
      { 
       connection.Close(); 
      } 
     } 

     loaddata(); 
    } 
0

您可以隨時將DataSource設置爲null。

someGridView.DataSource = null; 
someGridView.DataBind(); 
+0

我想在單擊按鈕時將其刪除...並且數據也應該從數據庫(這是一個基於服務器的數據庫)中刪除。 – Som

+0

@Som - 同樣刪除後端中的數據也是一個完全不同於你問的問題...... –

0

我只能是作爲問題的含糊,我還是不太明白,爲什麼我不能發表評論,但我可以留下一個答案......

無論如何,我們不」不知道你用什麼來訪問你的數據庫或支持GridView的模型。

比方說,比如你有下面的類支持你的GridView(你的GridView由該數據的類型你已經設置的數據源):

public class MyData 
{ 
    public int ID { get; set; } 
    public string SomeData { get; set; } 
} 

在你的ASPX你有以下:

<asp:GridView ID="GridView" runat="server"></asp:GridView> 
<asp:Button ID="DeleteButton" runat="server" OnClick="DeleteButton_Click"/> 

,然後在後臺代碼,你會做這樣的事情...

protected void DeleteButton_Click(object sender, EventArgs e) 
{ 
    var gridViewItemsToDelete = (IEnumerable<MyData>)GridView.DataSource; 

    foreach (var idToDelete in gridViewItemsToDelete.Select(r=>r.ID)) 
    { 
     // Delete the item by its ID 
     // I don't know what you're using to access your database 
    } 

    // Save Changes if you didn't in the foreach loop... 
} 
相關問題