我想在网页上实现一个按钮,删除gridview上显示的所有数据。有没有更简单的方法可以使用按钮一次删除所有数据?
答案 0 :(得分: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();
}
答案 1 :(得分:0)
您始终可以将DataSource设置为null。
someGridView.DataSource = null;
someGridView.DataBind();
答案 2 :(得分: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...
}