从gridview中删除所有数据
答
这样做很简单。只需遍历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();
}
答
您可以随时将DataSource设置为null。
someGridView.DataSource = null;
someGridView.DataBind();
+0
我想在单击按钮时将其删除...并且数据也应该从数据库(这是一个基于服务器的数据库)中删除。 – Som
+0
@Som - 同样删除后端中的数据也是一个完全不同于你问的问题...... –
答
我只能是作为问题的含糊,我还是不太明白,为什么我不能发表评论,但我可以留下一个答案......
无论如何,我们不”不知道你用什么来访问你的数据库或支持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...
}
并不是说你发布的代码量有多大关系,但VS2015是'IDE',而不是'Framework'版本。 –
我已经删除了Visual Studio 2015标签,因为此问题与编码相关,并不是特定于VS. –
我们需要你的代码。我们如何知道是否有更简单的方法来做事情,如果你没有发布代码来比较它? – Matthew